Recent Posts

Saturday, 28 May 2016

Command Line Arguments


* The arguments which are passing from command prompt are called command line arguments. 

* The main object of command line arguments are we can customize the behaviour of main.
Eg: 
java Test a b c
Here a = arg[0];
b = arg[1];
c = arg[2];
args.length = 3;
class Test {
   public static void main(String args[]) {
      for(int i = 0; i <= args.length; i++) {
         System.out.print(args[i]);
      }
   }
}

O/P
java Test // Nothing Display
java Test A B // A B 
* Within the main() command line arguments are available in string form.
E.g:
class Test {
   public static void main(String args[]) {
      System.out.print(args[0]+args[1]]);
   }
}
O/P
java Test 10 20 // 1020
* Space is the separator between command line arguments, if the command line arguments itself contain space then we should enclose with in double quotes.
E.g:
class Test {
   public static void main(String args[]) {
      System.out.print(args[0]);
   }
}
O/P
java Test "Ashok Kumar" // Ashok Kumar 
class Test {
   public static void main(String args[]) {
      String argh = {'A','B'};
      args = argh;
      for(String s : args) {
         System.out.println(s);
      }
   }
}
java Test X Y
O/P A B

java Test X Y Z
O/P A B

java Test
O/P A B
Note
* The maximum allowed number of command line arguments is 2147483647 which is maximum size of integer data type and minimum is 0

Next Tutorial  Java Coding Standards

Previous Tutorial  About Main Method

No comments:

Post a Comment