When we compile java program we use javac file.java
command but while running we use java file
.
So why it is necessary to explicitly specify file extension while compiling and not needed when we run the java program?
So why it is necessary to explicitly specify file extension while compiling and not needed when we run the java program?
Because that is the way that the tools are implemented:
javac
command expects file pathnamesjava
command expects Java class names1.They were implemented like this 20 something years ago, and the need for backwards compatibility has outweighed the need for change2.
It wasn't necessary to design the tools that way. (They could have done it differently.) But the discussions of why they designed it that way are:
1 - This is an over-simplification. You can use the -jar
option and provide an executable JAR file instead of a class name. Also, from Java 9 onward, the java
command can compile and run a single Java source file in one operation.
2 - One could make a case that it would be better for beginners if the tools worked differently. However, it is really not that hard to understand the tools if the newbie pays attention .... and bothers to read the documentation and/or a decent tutorial and/or listens in class.
Because when you "run" the java .class compiled file you are telling the Java application launcher which class contains the main method. The launcher starts the Java runtime environment and loads the specified class.
If you write
java MyClass
, then the class with the main method isMyClass
. Note that it would be erroneous to writejava MyClass.class
, sinceMyClass.class
is not the name of the class.When you compile with
javac MyClass.java
you need to tell the java compiler the extension, because it is a file and it need to find it.