Running basic java programs from commands line is a 3 steps process:
-
Write code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World”);
}
} -
Compile by
javac HellWorld.javawhich would check for errors & generateHelloWorld.classfile. -
run code by giving the class name –>
java HelloWorld
Now,
I am curious to know why:
java HelloWorld works but when we give fullpath of the classfile, it throws an error
$ java HelloWorld.class
Error: Could not find or load main class HelloWorld.class
What does it make a difference if we give just the classname Vs classname with file-extension?
The argument you give to the
javabinary isn’t meant to be a filename. It’s meant to be a class name. So in particular, if you’re trying to start a class calledBazin packagefoo.baryou would run:So similarly, if you try to run
java HelloWorld.classit’s as if you’re trying to run a class calledclassin a packageHelloWorld, which is incorrect.Basically, you shouldn’t view the argument as a filename – you should view it as a fully-qualified class name. Heck there may not even be a simple
Baz.classfile on the file system – it may be hidden away within a jar file.