Issue
If I remember correctly
javac filename.java
-> compile and generates classname.class(es)java classname
without .class extension
But when I try java filename.java
executes successfully while java classname
command gives the following error ,
Error: Could not find or load main class HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld
java -version
openjdk version "11" 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
System.out.println("Hello, World");
}
}
javap HelloWorld.class
is giving below output
Compiled from "HelloWorld.java"
public class HelloWorld {
public HelloWorld();
public static void main(java.lang.String[]);
}
java HelloWorld.java
-> executes fine, no class file generated.java HelloWorld
-> didn't execute.
Any idea why the program is behaving like this?
Solution
After some help from some stackoverflow veterans in the comment section I was able to understand what went wrong.
The latest version of Java have introduced launching single file source code directly using Java command.
from oracle docs.
To launch a single source-file program:
java [options] source-file [args ...]
To run Helloworld.java, you can now directly call execute java Helloworld.java
it will execute the java program and gives output without generating .class
file in the current directory.
Why old way of running java class file didn't work for me?
I had a class path variable 'CLASSPATH
' in my environment, so when I execute java HelloWorld
it is not looking for class in current directory. Give java -cp .
to explicitly give current directory to classpath.
java -cp . HelloWorld
Credits: Jon Skeet,Joachim Sauer, rzwitserloot
Answered By - Jishnu Prathap
Answer Checked By - Senaida (JavaFixing Volunteer)