Getting user input working with command line arguments in java is discussed below:
- User input can be provided through command line arguments.
- The command line arguments are specified after the class name when invoking the java application
- The runtime system passes them to the applications main method via an array of strings.
public class StudentName
public ststic void main(String args)
System.out.print("The Student's name is:");
Here, print( ) method displays the value provided to it as an argument and does not print a '\n' character at the end, unlike println() method. printf() method can also be used to display formatted output. When executing this program, the command should be as follows:
Z:/>java StudentName Preethi Priyanka
After the class name 'Studentname', two values are supplied by the user. If no two values are given while executing, a runtime error will be produced as the program expects 2 command line arguments, args and args. These two values will be received by the args array. It is an array of string of objects. so, the values given in the command line are received as string values and stored in the args array. Therefore, args will have string "Preethi" stored in it while args will have string "Priyanka" stored in it.
To display them together as a single name, '+' operator is being used. '+' operator, when used with two strings, concatenates them, whereas when used with two numeric values, adds them. In the above program, args and args are strings. So, '+' concatenates them. The println() method could have been written like below to concatenate a single space character between them:
This will insert a space between the two names, giving an output like "Preethi Priyanka".
Scanner class can also be used to get user input in Java.