1

We declare main function as public and static because Java interpreter should have access to it and there need not be object of the class to call main function. When I created main function within inner class and run the class, then also main function got executed. How does interpreter work internally to pick the main function and to execute?

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
swasthi
  • 43
  • 5
  • 1
    Java is not an interpreted language. – August Sep 29 '14 at 11:05
  • http://stackoverflow.com/questions/11952804/java-explanation-of-public-static-void-mainstring-args – seenukarthi Sep 29 '14 at 11:05
  • Do you have any code to back your explanation. I am unclear as to what the actual question is. – Chris K Sep 29 '14 at 11:05
  • 1
    @August that is not entirely true.. Java can be an interpreted language, and infact most JVMs ship with both an interpreter (for fast startup) and a JIT which is used to optimise 'hotspots'. – Chris K Sep 29 '14 at 11:07
  • 2
    @August Not really true. Java is a "hybrid": Code gets _compiled_ to bytecode, which then gets _interpreted_ by the JVM. – BackSlash Sep 29 '14 at 11:07
  • A `public static void main(String[])` in an inner class Inner inside a class Outer is just as static. In fact you will see a class file `Outer$Innner.class` compiled, containing such a function. Also in that main, there will be no `this` or `Outer.this`. – Joop Eggen Sep 29 '14 at 11:14

2 Answers2

2

First, let me fix your question. As it was already mentioned by @August java is not an interpreted language. I believe that asking about interpreter you want to ask about JVM (Java Virtual Machine).

Now the answer. I guess that JVM uses reflection call to execute main() method, i.e. uses code similar to the following:

Class mainClass = Class.forName(mainClassName); // mainClassName is taken from the command line argument. 
Method main = mainClass.getMethod("main", String[].class);
method.invoke(args); // args are taken from command line
AlexR
  • 114,158
  • 16
  • 130
  • 208
1

Signature of main method in Java

The main method has to strictly follow its syntax; otherwise the JVM will not be able to locate it and your program will not run. Here is the exact signature of main method:

public static void main(String args[])

If a program does not have this signature then the JVM will not able to find main method.

In this signature ..........

public defines that this method is accessible out of class, static shows that this method is accessible without creating any object of class, void shows that this method will not return any value, String args defines no. of argument is passed by user.

If the above signature does not match the JVM will return main method not found exception.

August
  • 12,410
  • 3
  • 35
  • 51
Gauri Shankar
  • 91
  • 3
  • 9