0

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?

TheUltimateGuide
  • 333
  • 3
  • 13

2 Answers2

3

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.

mike1234569
  • 636
  • 2
  • 5
2

There is little difference between running it as a compiled .class vs the original source code .java.

However, the ability to run a .java source file directly is a convenience, and has limitations:

  • The most severe limitation is that it only supports single-source programs. If you have classes in multiple source files, you cannot use this feature.

  • There is only limited support for specifying compiler options. For more advanced use, you need to invoke the compiler directly.

  • Re-running the program requires re-compiling the source, so starting the program will be a little slower.

But, other than those limitations, there is really no difference, except the convenience of only having to run one command.

Of course, since you should be developing Java programs using an IDE, it really doesn't matter. Which means that the feature reverts to it's original purpose, as specified in JEP 330: Launch Single-File Source-Code Programs, i.e. that of running #! shebang scripts.

Laf
  • 7,965
  • 4
  • 37
  • 52
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • `If you have classes in multiple source files, you cannot use this feature` --> I believe you meant you _cannot_, I took the liberty to fix this. – Laf Sep 18 '20 at 18:12