Command Line Arguments

In Java, command line arguments are used to take user input before running the program in a single line. When we run the program in compiler, we write “javac filename.java” and if it compiles successfully we have to write “java classname”. After writing “java classname” , we will pass arguments like any string or number and it will show that in the output screen.

Let’s understand this concept with the help of an example.

class Command{ 
public static void main(String[]ar)
{ 
System.out.println("First argument : "+ar[0]); 
}
}

Output:

javac command.java
java Command Codespeedy
First argument : Codespeedy

 

The above code will work just fine. You have to put an argument after compiling and it will be shown on the output screen. You can add as many arguments as you want just by increasing the index number like ar[1], ar[2], etc.

Note: If you didn’t pass any argument, the compiler will throw an exception of array out of bound index so make sure to write an argument after compiling.

Also read: getproperty() and getproperties() methods in Java

Leave a Reply

Your email address will not be published. Required fields are marked *