Search code examples
javajavac

java file compilation with file extension


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?


Solution

  • 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.