Saturday, August 2, 2014

Important points about the main method - 1/2

Let's see a "Hello world!" program:

 public class HelloWorld {  
     public static void main(String[] args) {  
         System.out.println("Hello world!");  
     }  
 }    

Running the program...


 C:\Dropbox\practice\blog>javac HelloWorld.java  
   
 C:\Dropbox\practice\blog>java HelloWorld  
 Hello world!  
   
 C:\Dropbox\practice\blog>  

1. HelloWorld is an executable class because it contains the main method.

2. The main method is executed first thing when a program is run.

3. The main method is thus called the entry point of a program.

4. It must be declared exactly as described above.

Otherwise the class will compile but we will get a runtime error:


 public class HelloWorld {  
     //Not public, but will compile  
     private static void main(String[] args) {  
         System.out.println("Hello world!");  
     }  
 }   

Running the program....


 C:\Dropbox\practice\blog>javac HelloWorld.java  
   
 C:\Dropbox\practice\blog>java HelloWorld  
 Error: Main method not found in class HelloWorld, please define the main method  
 as:  
   public static void main(String[] args)  
   
 C:\Dropbox\practice\blog>  

The method signature should not vary. 

5. The String array args passed as argument is the list of command line arguments given when executing the program  


 public class HelloWorld {  
    public static void main(String[] args) {  
       System.out.println("No. of arguments passed: " + args.length);  
         
       if(args.length != 0){  
          System.out.println("Arguments passed: ");  
          for(int i=0; i<args.length; i++){  
             System.out.println(i + ": " + args[i]);  
          }  
       }  
    }  
 }   

Output:


 C:\Dropbox\practice\blog>javac HelloWorld.java  
   
 C:\Dropbox\practice\blog>java HelloWorld  
 No. of arguments passed: 0  
   
 C:\Dropbox\practice\blog>java HelloWorld 0 1 2  
 No. of arguments passed: 3  
 Arguments passed:  
 0: 0  
 1: 1  
 2: 2  
   
 C:\Dropbox\practice\blog>  

I will cover more details on the topic in the following post. Experiment with the code so that you may feel comfortable before reading on.

No comments :

Post a Comment