Friday, June 18, 2010

How main method will execute?


How main method will execute?
Why i am asking this question is, we are not passing any arguments to main method.
If you defined a method, which is taking a String array as parameter. If you want to call that method, you must pass a String array (at least null) to that method. Without passing arguments you will not call that method. In the same way, how the main method is executing without passing any arguments (even not null also).

public class Test {
  public static void main(String args[]) {
    System.out.println("args : " + args);
    System.out.println("args.length : " + args.length);
  }/*main()*/
}/*Test*/



OUT PUT
---------
java Test (press enter)
args : [Ljava.lang.String;@10b62c9
args.length : 0

Here i will give you some explanation for the above question

If you observe the above output, here i am not passing any arguments to main method while execution. JVM will check, whether the programmer is passing any arguments to the main() method or not. If your not passing, then, it will create a String array with 0 (zero) index. Means, a String array without any strings in it.
That is the reason why, its showing args : [Ljava.lang.String;@10b62c9, this is the proof that the args is not null. And its length is 0 (zero).


public class Test {
  public static void main(String args[]) {
    System.out.println("args : " + args);
    System.out.println("args.length : " + args.length);

    if (args.length > 0) {
      for (int index = 0; index < args.length; index++) {
        System.out.println("args[" + index + "] : " + args[index]);
      }/*for-loop*/
    }/*if-state*/
  }/*main()*/
}/*Test*/


OUT PUT
---------
java Test hi Hello(press enter)
args : [Ljava.lang.String;@10b62c9
args.length : 2
args[0] : hi
args[1] : Hello

If you pass any arguments to the main() method, JVM will create String array with the arguments passed by you. These are called command line arguments. You can pass command line arguments as above.

1 comment:

  1. and when we run the class the jvm ececute the class with out object existing for that class be coz main method is static ..jvm executes static methods without objects.thats why main method is must be public static.

    ReplyDelete