Input from the terminal in Java

The main method has a mechanism to accept input when run from the terminal.

terminal

Run from terminal

Let’s say I have this class

public class Main {
public static void main(String[] args) {
System.out.println("hello, world!");
}
}

This code is saved in Main.java file under my desktop. In order to run it from the terminal, I will need to navigate with my terminal to my desktop and execute these commands:

javac Main.java — to compile the source code into java byte code.

java Main — to run without any arguments.

Run from the terminal with arguments

public class Main {
public static void main(String[] args) {
String name = args[0];
System.out.println("hello, " + name);
}
}

Now, I have a little different code. The main method has String[] argument. Basically, when running the code from the terminal we pass data for this argument.

terminal

java Main John — run with one argument. The above code will print hello, John . After the name of the class name, we can list arguments separated by a space. Each argument will be assigned to a string array.

Let’s see another example

public class Main {
public static void main(String[] args) {
System.out.println("1. " + args[0]);
System.out.println("2. " + args[1]);
System.out.println("3. " + args[2]);
System.out.println("4. " + args[3]);
}
}
terminal

If we want to combine two separate words as one argument, we can use double-quotes.

terminal

Software Developer, Java Instructor https://www.techleadacademy.io/