Reputation: 34145
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.java
which would check for errors & generate HelloWorld.class
file.
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?
Upvotes: 0
Views: 297
Reputation: 4114
In the Java programming language, source files (.java files) are compiled into (virtual) machine-readable class files which have a .class extension.
When you run java class file after compile then run the following command:
java HelloWorld
Note: Need to setup java classpath
Upvotes: -1
Reputation: 718826
What does it make a difference if we give just the classname Vs classname with file-extension?
It is because that is the way it is. Sun / Oracle have implemented the java
command to work that way since Java 1.0, and changing it would be massively disruptive.
As Jon says, the argument to the command is a fully qualified class name, not a filename. In fact, it is quite possible that a file with the name HelloWorld.class
does not exist. It could be a member of a JAR file ... or in some circumstances, just about anything.
In Java 11 and later it is also possible to compile and run a single Java source file with a single command as follows:
java HelloWorld.java
(This possible because Oracle no longer supports Java distributions without a Java bytecode compiler.)
Upvotes: 2
Reputation: 1500675
What does it make a difference if we give just the classname Vs classname with file-extension?
The argument you give to the java
binary 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 called Baz
in package foo.bar
you would run:
java foo.bar.Baz
So similarly, if you try to run java HelloWorld.class
it's as if you're trying to run a class called class
in a package HelloWorld
, 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.class
file on the file system - it may be hidden away within a jar file.
Upvotes: 6