How can we use the command line arguments for giving input to a Java program?

In Java, if we want to supply any input to the program at the time of execution, we can use command line arguments.

Command-Line Arguments are the arguments which are supplied to the Java program, when it is called for execution.

We can pass the arguments from the console to the program and they are used as input.

When a Java program is run from the command prompt, the arguments are provided after the program's name having white-space as separator.


c:\\ java ProgramName <space> Argument1 <space> Argument2


Program Name :

class Demo
public static void main (String user_input[])
System.out.println("First Argument is "+user_input[0]);
System.out.println("Second Argument is "+user_input[1]);

 Compile :  

 Run : 
                    java Demo Programming Prashn

 Output : 

                   First Argument is Programming
                   Second Argument is Prashn

Explanation :  In the above example when we run our program with two command line arguments (given after the program name), they are stored in  user_input array (i.e. an array of string objects) and then they are shown as output using println() method.



Command line arguments are string objects by default.
If we pass any number as command line argument, it is not treated as an integer (i.e. 1), it will be treated as string(i.e. "1"), and we have to convert it into an integer for performing numeric operations on it.
For converting a string to an integer, we can use the Wrapper class methods, e.g.


This method converts a string ( having numeric characters ) into an integer, i.e. from "100" to 100.