Tuesday, November 24, 2015

Why main method is public static void main ?


Important points needs to be remember about main() in Java
  • Main method in Java is public so that its visible to every other class, even which are not part of its package. If its not public ,JVM classes might not able to access it.
  • Main method is static in Java, so that it can be called without creating any instance. While JVM tries to execute Java program it doesn't know how to create instance of  main class as there is no standard constructor defined for main class.
  • Main method is void in Java because it doesn't return any thing to caller which is JVM .
  • Main method in java doesn't return anything and has return type void while main method in C and ++ return int.
Main method is a standard method and has pre specified signature, if you change the signature of main method JVM will not be able to locate main method will throw Exception at runtime as shown in above example. main method is public, static and void and accept an String[] as argument and from Java 5 onwards it can also accept variable arguments instead of array. following signatures are valid main method signature in Java :

public static void main(String args[]) {}

public static void main(String[] args){}

public static void main(String... args){}

You can also use certain modifier like final, synchronized and strictfp along with main method in Java.

public class MainClass {
  public static final synchronized strictfp void main(String... args){
       System.out.println("I am main class which contains main method");
  }
}

1 comment:

  1. Strictfp is a keyword in the Java programming language that restricts floating-point calculations to ensure portability.
    Strictfp ensures that you get exactly the same results from your floating point calculations on every platform. If you don't use strictfp, the JVM implementation is free to use extra precision where available.

    ReplyDelete