Most websites on the internet say:
"use the
javaccommand to compile a.javafile. Then run it using thejavacommand"
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.javaand then from the command line compile it like thisjavac Myclass.javaand then run it like thisjava Myclass.javacstill used to compile if you don't want to deploy source code, or you have more than a single file (documentation ofjavafor source-file option: Only used to launch a single source-file program.)javaccompiles the Java source into JVM specific interpreted bytecode and thejavacommand loads it inside the JVM's ClassLoader.