Java | Getting user Input

05 min read

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.

Example:

public class StudentName
{
public ststic void main(String args[])
{
System.out.print("The Student's name is:");
System.out.println(args[0]+args[1]);
}
}

 

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[0] and args[1]. 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[0] will have string "Preethi" stored in it while args[1] 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[0] and args[1] are strings. So, '+' concatenates them. The println() method could have been written like below to concatenate a single space character between them:

System.out.println(args[0]+" "+args[1]);

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.

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error