java file compilation with file extension

4.1k views Asked by At

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?

2

There are 2 answers

4
JosEduSol On BEST ANSWER

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.

0
Stephen C On

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:

  • The javac command expects file pathnames
  • The java 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:

  • discussions (off topic)
  • opinion based (off topic), and
  • moot.

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.