Open In App

What will happen if i declare main() in java as non-static?

main() method in Java acts as an application’s entry point. So declaration must read “public static void main(String[] args)” to work properly .

What happens if you declare main to be non-static is as follows?






import java.util.Scanner;
public class Sample{
   public void main(String[] args){
      System.out.println("This is a sample code");
   }
}

Compilation Error:

If we declare main as non-static (public void main(String[] args)), our code will not compile. This is because the Java Virtual Machine (JVM) needs to call the main method without creating an instance of the class. If main is non-static, it would require an instance of the class to be created, which contradicts the purpose of the entry point method.



Reasons Why main() Method Should be Static:

Example of using static:




// Java Program to implement
// Direct Addition to Add two Numbers
import java.io.*;
 
// Driver Class
class GFG {
    public static int sum(int num1, int num2)
    {
        return num1+num2;
    }
     
    // main function
    public static void main(String[] args)
    {
        GFG ob = new GFG();
        int res = ob.sum(28, 49);
        System.out.println(res);
    }
}

Output
77




Conclusion:

Declaring the main method in Java as non-static is not possible. The Java compiler will generate an error message if you try to do so.

This is because the JVM expects the main method to be static. If main() is non-static, it would require an instance of the class to be created before execution, which contradicts the fundamental purpose of the main() method as the starting point of the program.


Article Tags :