Pages

Sunday, February 5, 2017

main method in java explained

Exploring main() method

  • main() is a special method which is called by JVM.
  • main() has the standard signature as follows:
    • public static void main(String args[])
    • static public void main(String args[])
  • main method can be overloaded, but JVM always invokes main() method() with the standard signature.
  • main() method works as application launches i.e starting point of the application.

Explanation of main method

  • public - It can be accessed from anywhere.
  • static - It can be accessed using Class Name directly.
  • void - It will not return any value to caller.
  • main - Method name (Taken from C/C++).
  • String[] - To pass command line values.

Example 1:

main method signature has to be the standard one.
class Lab2
{
    static{
        System.out.println("Iam SIB");
    }

    public static void main(String args) 
    {
        System.out.println("Iam main method!");
    }
}

/*
compilation is successful.

output:
Error: Main method not found in class Lab2, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
*/

Example 2:

var args can be used instead of String[] args
class Lab4
{
    public static void main(String...args) 
    {
        System.out.println("Iam main method!");
    }
}

/*
output:
Iam main method
*/

Example 3:

main method can be made final. It cannot be overriden anyway.
class Lab5
{
    final public static void main(String...args) 
    {
        System.out.println("Iam main method!");
    }
}

/*
output:
Iam main method
*/

Summary

  1. Running Java Application
    Ex: java Hello
    Before JAVA 7
    • Loads the class
    • Checks whether main() method with standard signature is available or not.
    • If available then invokes main method.
    • If not available then JVM will throw "java.lang.NoSuchMethodError:main" error

    Java 7 onwards
    • Checks whether main() method with standard signature is available or not.
    • If available, then invokes then loads the class first and invokes the main() method.
    • If not available, then JVM will throw Error:
      Main method not found in class Hello, please define the main method as:
      public static void main (String args[])
  2. You are allowed to use Var-Args as main method parameter.
  3. You can use following modifiers for standard main() method.
    • public
    • static
    • final
    • strictfp
    • synchronized
  4. You cannot use following modifiers for standard main() method.
    • abstract
    • native
    • private
    • protected
  5. You can invoke main() method explicitly.
  6. You can overload main method.

No comments:

Post a Comment