0

I popped into the terminal and ran a hello world script using the following command java Hello, and it ran like normal java programs. I proceeded to run java Hello.java, and then Java took a while (1.0 seconds).

Why does using the second command, java Hello.java, take longer to execute than using java Hello.

Sbu_05
  • 31
  • 3
  • 1
    You can't execute `.java` files. Those files need to be compiled first. I'm surprised `java Hello.java` even ran without manually compiling this file beforehand. – tkausl Sep 07 '21 at 19:01
  • 1
    It doesn't. That's not a valid performance test. – Software Engineer Sep 07 '21 at 19:01
  • 2
    @tkausl as of Java 11, you can compile and run Java files like this. See e.g. https://stackoverflow.com/questions/54493058/running-a-java-program-without-compiling/54493093 – Andy Turner Sep 07 '21 at 19:08
  • Does this answer your question? [Running a Java program without compiling](https://stackoverflow.com/questions/54493058/running-a-java-program-without-compiling) – Gunesh Shanbhag Sep 07 '21 at 19:15

2 Answers2

5

Why does using the second command, java Hello.java, take longer to execute than using java Hello.

java Hello.java only works in Java 11+: it is compiling Hello.java, then running it.

java Hello isn't compiling anything. It's just running something that was previously compiled. This is quicker because it's doing less: it's not compiling, just running.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Before JAVA 11, the procedure to execute Java files through command line was:

First compile the java file.

javac nameOfFile.java

The above command creates a nameOfFile.class file. You will see the file if run either ls or dir depending on your OS. When you run

java nameOfFile

It interpretes the nameOfFile.class file and gives you output.

From JAVA 11, you get the option to launch a single source code file directly, without intermediate compilation. Hope this answers your question

Gunesh Shanbhag
  • 559
  • 5
  • 13