If we declare the class with default scope(non-public) and public main method it executes successfully. Here class scope is mote stricter than main method scope.
But if we declare main method as default, then JVM will throw error. Why?
class DefaultTest {
public static void main(String[] args) {
System.out.println("output.........");
}
}
Runs successfully but
class DefaultTest {
static void main(String[] args) {
System.out.println("output.........");
}
}
this won't.
I mean if the class itself is not public JVM can still access main method that means there is no need of main to be public. But if we don't declare it as public, it will throw an error.
You can define the main method in your program without private, protected or, default (none) modifier, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this as the entry point of the program.
Why is main method public in Java? We know that anyone can access/invoke a method having public access specifier. The main method is public in Java because it has to be invoked by the JVM. So, if main() is not public in Java, the JVM won't call it.
Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated. And main method is static therefore, you cannot use the "this" reference in main method.
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.
It is specified by the Java Language Specification, see http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html chapter 12.1.4. Invoke Test.main:
The method main must be declared public, static, and void.
It is also required by the JVM specification, see the answer from @A4L.
static
so that the JVM can run the method without having to instantiate the class object
+ public
so that the JVM can access it freely without any access issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With