Command Line Argument Simplified in Java


Command line arguments are the information that we pass to the Java program during runtime. Mostly when we write java code in a standalone mode or non-GUI mode, we use Command line arguments to pass information to our program during run time. Java developers tried to create an interface between the code and the users by providing inputs to the programs instead of hard coding.

Standalone codes are mainly used to build the following.

  • a prototype
  • a stub
  • a driver
  • proof of concepts
  • command based coding
  • configuration information for launching some application especially games.

In all the above cases we don't need a full phased GUI to work with. We need some piece of code that shows the working model is correct. This is also applicable to the old days of coding when GUI coding did not flourish that much, coder used to provide all necessary information via command line arguments. So there are a lot of data goes back and forth in a command line programming.

Lets us look at the main method declaration for java:
It says "public static void main(String args[]) "
 this means main() method will take an argument called args. args is an array and it is of String type.
But array -args size is not defined. This says that main() can take N number of arguments from the user. In another word, the arguments are stored in an array and passed to main() method for execution. The arguments are of type String and space is used as a separator. Who does all these transformations for us? Well, it is JVM. It reads the String, splits with space returns args array to main.

class myClass{
public static void main(String args[])
{
System.out.println(args[0]);
System.out.println(args[1]);

}
}
 
to execute this,(after compilation) in command prompt we need to provide the command to execute this code along with the arguments that need to be passed to main() method.
java myClass Test arguments
The output of the code will be
Test
argument
We can certainly make the code better by providing some logic to it.

class myClass{
public static void main(String args[])
{
if(args.length>0){
System.out.println("argument/arguments found");
for(int i=0;i<args.lenth;i++)
System.out.println(args[i]);
//or
for (String myArgValue:args)
System.out.println(myArgValue);

}
else
{
System.out.println("argument/arguments not found");
}
}
}
lets check one more example with While loop:

class myClass{
public static void main(String args[])
{
int count,i=0;
String myString;
count=args.length;
while(i<count)
{
myString=args[i];
System.out.println("The input from the user is"+myString);
}
}
}


Command Line Argument Simplified in Java Command Line Argument Simplified in Java Reviewed by Animesh Chatterjee on August 30, 2018 Rating: 5

No comments:

Powered by Blogger.