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?
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?
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 is MyClass
. Note that it would be erroneous to write java MyClass.class
, since MyClass.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.
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 names.They were implemented like this 20 something years ago, and the need for backwards compatibility has outweighed the need for change1.
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 - 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.