Monday, December 9, 2013

The Java program doorway - main method

In any Java Application, there should be at-least one main method available and can be in any of the classes. The JVM starts the execution from the first statement of the main method and ends after the last statement. A Sample main method...

public class MyFirstApp
{
public static void main(String[] args)
{
System.out.println("Main method inside class MyFirstApp");
}
}

The keyword 'public' specifies that the main method can be accessed from anywhere. 

The 'static' keyword implies that the main method can be accessed without instantiation i.e objects are not needed to access the main method.

'void' denotes that the main method doesn't return any value.  

String[] is an array of strings (sequence of characters) and is named 'args' (This name "args" can vary"). In Java, the main method needs a single array of strings as parameter.

Queries:

Can we declare a main method as Private?
                               or
Can we remove static keyword from the main method?
                               or
Can we remove the argument String[] args from the main method?

If we do any of the above, the compiler will run properly. But at run time, the JVM throws the error message.

What will happen if I write "static public void" in place of "public static void"?

The program will run and execute properly with no errors.

Can I have many main methods in the same class?

No, Compiler error occurs.

Note:

The name of the class containing the main method must be the same as the name given to the program file itself.

No comments:

Post a Comment