Java provides an option like, a java
application can accept any number of arguments from command line. This option facilitates us to configure Application at the time of
running.
User should pass command line arguments, at the time of launching
application.
Syntax
java ClassName arguments
When
an application launched, The command line arguments are copied to the
String argument of the main method.
Example 1
class CommandLine{ public static void main(String args[]){ System.out.println("Number of arguments passes is " + args.length); for(int i=0; i < args.length; i++){ System.out.println(args[i]); } } }
Run
the Application like below
java
CommandLine Hi How Are You
Output
Number of arguments passes is 4 Hi How Are You
As
you see args[0] contains String “Hi” args[1] contains “How”
etc.,
Example 2
class CommandLine{ public static void main(String args[]){ if(args[0].equals("Day")) System.out.println("Good Morning, Have a Great Day"); if(args[0].equals("Night")) System.out.println("Sleep Well, Good Night"); } }
Run 1
java
CommandLine Day
Good
Morning, Have a Great Day
Run
2
java
CommandLine Night
Sleep
Well, Good Night
Some
Points to Remember
1.
If no command line arguments are provided then, length of args is
zero
class CommandLine{ public static void main(String args[]){ System.out.println(args.length); } }
Output
0
2.
If there is no command line arguments, then the String array of Main
method will be empty or null?
It
is Empty,not null.
No comments:
Post a Comment