java.class-file

Is there a meaningful difference between running .class or .java?


I'm starting Java, and was reading the "Hello World!" for Microsoft Windows guide from Oracle. In the guide, it tells you to use javac to compile into a .class, then run with

java -cp . HelloWorldApp

When I tried running it, I didn't run the proper file and instead accidentally ran

java helloworldapp.java

After I noticed that, I tried the original way and they both printed

Hello World!

This got me thinking, is there any difference to running it as a compiled .class vs the original source code .java?


Solution

  • In Java 11, it is now possible to run 'java <source_file>' mostly as a way to help gain familiarity with the language: https://openjdk.java.net/jeps/330

    Behind the scenes it is first compiling the source file then running the compiled class. For simpler use cases (ex: 1 file java program, with no dependencies) the behavior is likely to be the same, but it is worth noting that this is not meant as a replacement of 'compile then execute' in general.