Command line argument is the facility in java to pass the string value while executing the class file after the compilation.While executing the class file we can give as many string value separated with the space. These values are passed to the main method with array of String as an argument and the size of the array will be decided as per the value provided while executing. JVM will invoke the main () with array of string and can able to print by using the array index individually or with the help of for loop. We can also print the length of the array.

Example of the command line argument

public class prog {

public static void main(String sush[ ]) {
System.out.println( sush [0] ) ;

   }
}

Compiler -- javac prog.java

Execute---- java prog  javatutorial

Here we are executing our java program by passing javatutorial as a string value, which get stored in the first index of our array of string defined in the main() i.e sush[ ] .Like this we can be able to pass as many string value as we want. If you want to print any integer value then simply pass internally it will be converted into string.

Note : Size of the array depend on the number of value you are passing. If you are passing one value and trying to print more then one index then it will run-time exception as "ArrayIndexOutOfBoundsExecption ".For ex -

public class prog {

public static void main(String sush[ ]) {
System.out.println( sush [0] ) ;
System.out.println( sush [1] ) ;    // Run-time exception

   }
}

Compiler -- javac prog.java

Execute---- java prog  javatutorial

While executing the above statement JVM will throw run-time exception as we are passing only single value any trying of print more than the size of the array.

All the above program are valid with any version of JDK but java vendor has introduced a new feature from java 5 of variable length argument. So in the main method we can also VAR_ARGS as a parameter.Internally it is converted into array by the compiler.It is represented with three dots. For more about VAR-ARGS Click Here ! .For ex-

public class prog {

public static void main(String... sush) {
System.out.println( sush [0] ) ;

   }
}

Compiler -- javac prog.java

Execute---- java prog  javatutorial

So keep experimenting with the codes in java !

0 comments:

Post a Comment

Blog Archive

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic