Open In App

Understanding “static” in “public static void main” in Java

Following points explain what is “static” in the main() method: 
 



// Making a function as static
static void func()
{}

// Making a variable as static
static int var;



// Making a static function
class GfG
{
    static void func()
    {}
}

// Calling a static function
GfG.func();



class GfG
{
    // Making a static main function
    public static void main(String[] args)
    {}
}



Need of static in main() method: Since main() method is the entry point of any Java application, hence making the main() method as static is mandatory due to following reasons: 
 

public class GfG{
  protected GfG(int g){}
  public void main(String[] args){
  }
}



What if we don’t write “static” before the main method: If we do not write “static” before the main method then, our program will be compiled without any compilation error(s). But at the time of execution, the JVM searches for the main method which is public, static, with a return type and a String array as an argument. If such a method is not found then an error is generated at the run time.






/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public void main (String[] args) {
        System.out.println("GFG!");
    }
}

Output: An error message will be shown as follows

Article Tags :