JavaIntellectualTricks

Command Line Arguments


  • The arguments which are passing from command prompt are called command line arguments.
  • With these command line arguments JVM will create an array and by passing that array as argument JVM will call main().

Example:
>java Test A B C
A=args[0];
B=args[1];
C=args[2];

The main objective of command line arguments is we can customize behavior of the main().

Q. Why java main( ) takes always String as parameter?

Case 1:
class Test {
 public static void main(String[] args) {
  for (int i = 0; i <= args.length; i++) {
   System.out.println(args[i]);
  }
 }
}
>java Test A B // o/p: A B  ArrayIndexOutsOfBoundsException
>java Test A B C // o/p: A B C  ArrayIndexOutsOfBoundsException
If we replace <= with < ,then we won't get any run time exception.

Case 2:
class Test {
 public static void main (String[] args){ 
  String[] argh={“X”,”Y”,”Z”}; 
  args=argh; 
  for(String s: args){ 
   System.out.println(s); 
  } 
 }
}
o/p:
>java Test A B // o/p: X Y Z
>java Test A B C // o/p: X Y Z    

Case 3:
With in main() command line arguments are available in String form.
class Test {
 public static void main(String[] args) {
  System.out.println(args[0] + args[1]);
 }
}
> javaTest 10 20 //o/p: 1020

Case 4:
Usually space itself is the separator between command line arguments. If our command line arguments itself contains the space then we have to enclose that command line arguments with in double quotes.
class Test {
 public static void main(String[] args) {
  System.out.println(args[0]);
 }
}
> java Test “Note Book” //o/p:  Note Book

5 comments:

  1. Thanks for sharing this java tricks. It is really helpful, continue hsaring more like this.
    Angularjs Training in Chennai | Angularjs course in Chennai

    ReplyDelete
  2. Thanks mate. I am really impressed with your writing talents and also with the layout on your weblog. Appreciate, Is this a paid subject matter or did you customize it yourself? Either way keep up the nice quality writing, it is rare to peer a nice weblog like this one nowadays. Thank you, check also event marketing and registration platform

    ReplyDelete
  3. informative blog , keep posting and dont forget to checkout our blog java classes in satara

    ReplyDelete