0
votes

Running basic java programs from commands line is a 3 steps process:

  1. Write code:

    public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } }

  2. Compile by javac HellWorld.java which would check for errors & generate HelloWorld.class file.

  3. 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?

3
java looks for the class HelloWorld. when you give HelloWorld.class it looks for the class 'HelloWorld.class"Senthil Kumar

3 Answers

6
votes

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.

2
votes

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.)

-1
votes

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