public static void main(String [] args) - Full Explanation

Why JVM Call main() method?

JVM is a program in which the main() method is configured that is the reason JVM called the main method. we can change the name of the main() method but we need to change the method calling in JVM.

Explanation of the main method :

public static void main(String [] args) is a method that is called by JVM. 

  1. Public: Public is an access modifier of the main method. the main method is public because the JVM can call this method from anywhere.
  2. static: without creating an object JVM can call this method that's why the main method is static. without an existing object also JVM has to call this method and the main method is not related to any Object.
  3. void: void is a return type of the main method, the main method not returning any value to JVM.
  4. main: this is the method name that is configured in JVM. 
String[] args: these are command-line arguments.

The above syntax is very strict if we performed any change we will get a Runtime exception i.e No such method error. the syntax is very strict but we can done some changes to the main method. below are some changes in the main() method.

  1. the order of modifiers is not important instead of "public static" we can write "static public".
  2. we can take instead of "args" any java identifier.
  3. we can replace string[] with var arg parameter.
  4. we can declare the main() method with the following modifiers
    1. final
    2. synchronized
    3. strictfp
  5. We can declare String[] in any acceptable form.
    1. main(String[] args)
    2. main (String []args)
    3. main(String args[])
Overloading of the main() method is allowed but JVM call only String[] argument method. another overloaded method we need to call explicitly. 
For Example :

class test{
    public static void main(String[] args){
        System.out.println("main with String[]");
    }
    public static void main(int[] args){
        System.out.println("main with int[]");
    }
}
The inheritance concept is applicable to the main() method. when we executing child class and child class not containing any main() method then JVM will call parent class main() method.
For Example :

class test{
    public static void main(String[] args){
         System.out.println("parent class method");
    }
    
}
class test2 extend test{
}

the Overriding main method is not applicable instead of method overloading a method hiding concept is applicable because both class's main() method is static.
For Example :

class test{
    public static void main(String[] args){
        System.out.println("parent class method");
    }
    
}
class test2 extend test{
    public static void main(String[] args){
         System.out.println("child class method");
    }
}



Comments

Popular posts from this blog

Primitive Data Types in java

let - Keyword in JavaScript (Block scope)

Coding Problem 4: Smallest window containing 0, 1 and 2 [GFG - Problem Solving]