Why we have to use -jar option when running a self-contained jar

We can run a self-contained jar file with a command like this:

java -jar foo.jar
,where foo.jar contains a main class that is specified in META-INF/MANIFEST.MF with a Main-Class entry. What will happen if running if without -jar option? java will read foo.jar as a main class named jar in package foo:
C:\tmp>java foo.jar
Exception in thread "main" java.lang.NoClassDefFoundError: foo/jar
I guess that's the reason why -jar option is necessary to tell JVM to look for a jar file rather than a class file foo/jar.class. But realistically, how often people name their main class jar? Why can't we disallow this naming and then omit -jar option when running a jar file? JVM should be able to figure it out by .jar extension.


Anonymous said...

Good point. Both .jar and .class files are created by the JDK, so the VM need not force the user to specify it. Sun could change the meaning of -jar to mean that "the file does not have the .jar extension, but pretend its a jar".

Having said that, one reason why the VM might be the way it is would be that -jar flag might be specific to Sun VMs, and might not be available on other implementations. Is that so?

Unknown said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

rohini said...

apple service center chennai | apple iphone service center chennai | apple ipad service center chennai | apple mac service center chennai | ipad service center

web development company in hyderabad said...

I have some confusion on this jar file. After reading this blog, I clarified my doubts regarding it.

Diyalabs said...

Thanks for sharing such a helpful, and understandable blog. I really enjoyed reading it.

Robots for kids
Robotic Online Classes
Robotics School Projects
Programming Courses Malaysia
Coding courses
Coding Academy
coding robots for kids
Coding classes for kids
Coding For Kids