What is public static void main(String args[]) in Java?

UPDATED: 07 October 2010
Transparent Java Logo

What is Java?
Java is most reliable programming language in IT sector. Java is now used by wide range of devices like Samsung, Nokia, etc... The best example of Java is Android. Android is Mobile Operating system built in Java(UI). Dr. James Gosling and his team invented Java in Sun Microsystem.

Why "public static void main" in Java Program?
If you are beginner then you must know. If any program has  "public static void main(String args[])" in program then its executable program. Lets understand why we write it. Assume below scenario and lets have class "demo".
class demo{
    public static void main( String args[]){
         System.out.println("Hello, World!");
    }
}
// Output - Hello, World!
Now lets use the above program without "public"
/* Code will compile but will give you runtime error. */
class demo{
    static void main( String args[]){
         System.out.println("Hello, World!");
    }
} 
// Error: Main method not public

Reason to declare main method as a public
  • javac demo.java command generates the demo.class file.
  • java demo (when user run this command JVM find the "main" method in demo.class file but as we didn't declare it as a public. It means main method is not allowed to access publically.) Declaring any method as public allow other method to call it inside and outside of class as well.

Reason to declare main method as a static
As you know to access any method you must have an object of that method. "static" keyword allows JVM to access method without creating object. Below example shows how static used.
class x{
    static int temp=10;
}
class demo{
    public static void main( String args[]){
         System.out.println("Hello, World!");
         x.temp=20;
         System.out.println(x.temp);
    }
}      
/* We are using "temp" variable of class "x" without creating object of class. */

void
void keyword tell that main method doesn't return any value.

main(String args[])
Program starts execution from here. Main method have argument in String array. So you can pass values in program at run time.


0 comments :