I have a question that why main method is marked as public?
According to an answer on stackoverflow, It is declared as static
When the code is executed, a JVM will be created and that will act as a container for the code we are trying to execute. Declaring this method as public allows the JVM to start the code execution. If method is private, JVM wont be able to call it. There are ways to call a private method as well (eg by using Reflection), but that is not a standard way to do things.
Because the JLS, Section 12.1.4, says so:
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.
If it's not public
, then it won't be found; you'll get
Error: Main method not found in class Main, please define the main method as:
public static void main(String[] args)
Because the main method should be accessed by JVM without any restrictions from any where. I think you can find more info here: Why main method is public