Can we declare a main method as private in Java?


Yes, we can declare the main method as private in Java.

It compiles successfully without any errors but at the runtime, it says that the main method is not public.

Example:

class PrivateMainMethod {
   private static void main(String args[]){
       System.out.println("Welcome to Tutorials Point");
    }
}

The above code is working successfully at compile time but it will throw an error at the runtime.

Output:

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

Updated on: 11-Feb-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements