I just picked up my Ubuntu machine after a long time for some java related work and found that I have java already installed but not javac.
I made a Test.java file with a main method and a simple print statement. I wrote this in my terminal:
java Test.java
I expected that without javac this shouldn't compile and run but it printed the output on my console. I then installed a JDK to enable the javac and ran this:
javac Test.java
This created a Test.class file. Still to run the Test class I need to type java Test.java
and on typing java Test
it throws java.lang.NoClassDefFoundError.
Can someone please explain to me what's happening in the background of these commands? Edit: Here are the contents of my Test.java:
package Learning;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World!");
}
}
What you experience here is a new feature, added for Java 11:
In Java SE 11, you get the option to launch a single source code file directly, without intermediate compilation. Just for your convenience, so that newbies like you don't have to run javac + java (of course, leaving them confused why that is).
Quoted from here. For more details, see the corresponding JEP 330.
So: if you have a single self-contained .java file ... then the java binary recognizes that, compiles it, and directly runs it (when using Java 11 or newer).
But keep in mind: it is just that, a way to quickly run a single class. It isn't meant to replace the "real" way of doing things.
In general, you still use javac
first, and then java
. Or, more real world: you use a built system where you describe what to build, and then the build system invokes javac
for you behind the covers.