Reputation: 5106
I have the following simplified file structure:
C:/red/green/black/yellow/white/pink
. I am now in cmd in folder 'black'.
The Hello.java
file has package yellow.white.pink
in it. In folder 'pink' there is a Hello.java
source file.
First I try to compile the file:
javac -classpath . -encoding ISO-8859-1 yellow.white.pink.Hello.java
javac -cp . -encoding ISO-8859-1 yellow.white.pink.Hello.java
These two give me an error:
File not found yellow.white.pink.Hello.java
.
Then I try
javac -encoding ISO-8859-1 C:/red/green/black/yellow/white/pink/Hello.java
It compiles just fine.
To run it I do
java -classpath . yellow.white.pink.Hello
And it runs just fine.
But in this case
java C:/red/green/black/yellow/white/pink/Hello.class
doesn't work - gives Could not find or load main class
error.
Why is that? Why can't I compile .java file when being in the root folder and giving a full package name and it works only with the whole path to the source, while the reverse is true for executing the program?
Upvotes: 1
Views: 202
Reputation: 10300
java
command takes as an argument the fully qualified name of the class (which is package name plus class name).
In both cases the fully qualified name must be yellow.white.pink.Hello
and it should not be changed.
However in your second run you pass C:/red/green/black/yellow/white/pink/Hello.class
which is path to the compiled file but not the fully qualified name of the class.
What is also different in this two runs is classpass
declaration. In the first run it is path of the current directory (can be passed as .
). In the second run it was not specified at all. Java treat this as current directory path.
To make the second example work you have to specify classpath
as well as class name.
java -classpath C:/red/green/black yellow.white.pink.Hello
Upvotes: 3