Most websites on the internet say:
"use the
javac
command to compile a.java
file. Then run it using thejava
command"
But today I tried to run a java program without javac
and I got a strange result.
Here are the contents of a file called hello.java
:
public class Myclass {
public static void main(String[] args){
System.out.println("hello world");
}
}
Then I ran:
$ javac hello.java
Which gives me this error:
hello.java:1: error: class Myclass is public, should be declared in a file named Myclass.java
public class Myclass {
^
1 error
But when I run it without the javac
command, it executed without any errors.
$ java hello.java
hello world
Does the java
command also compile the program? If yes, why do we need the javac
command?
The version of my java is:
openjdk version "12.0.2" 2019-07-16
OpenJDK Runtime Environment (build 12.0.2+10)
OpenJDK 64-Bit Server VM (build 12.0.2+10, mixed mode)
Myclass.java
and then from the command line compile it like thisjavac Myclass.java
and then run it like thisjava Myclass
. – unnssejavac
still used to compile if you don't want to deploy source code, or you have more than a single file (documentation ofjava
for source-file option: Only used to launch a single source-file program.) – user85421javac
compiles the Java source into JVM specific interpreted bytecode and thejava
command loads it inside the JVM's ClassLoader. – unnsse