Reputation:
I am a beginner in java i want to know whats the difference between the class files created for a class with main function and the one created for a class without main function.we can create a class without a main function and able to compile it so whats the difference between the class files being generated.It may look like a stupid question but i just want to know the answer for this.
Thank you in advance
Upvotes: 1
Views: 151
Reputation: 16060
There is no difference in the compiler.
In the compiled bytecode are methods.
If there ist a
public static void main(String[] args){}
You will get a Class, which can be started by calling
java ClassName
It is just a convention, that the main-method is started, if called by Java.
update
Prior to Java 7 you could start a JavaClass like this (without a main-method):
//Don't use this
public class RunnableNoMain{
static { new RunnableNoMain(); } //creates an instance.
}
The static initializer will create an instance and execute code. Right after, there will be a NoSuchMethodException (main ist not found)
Upvotes: 2
Reputation: 17422
There is no special bytecode for one class with a public static void main(String ..args)
, that method is compiled the same way as any other method.
The difference is made by the Java Virtual Machine (not the compiler), whose specification states this:
The Java Virtual Machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (§5.3.1). The Java Virtual Machine then links the initial class, initializes it, and invokes the public class method void main(String[]).
Upvotes: 4