Rustam Issabekov
Rustam Issabekov

Reputation: 3497

default classpath current directory anomaly

I am trying to compile and run simple Java program. This program basically prints out hello world phrase. I am not specifying -cp option and I don't have CLASSPATH environment variable. Hence the user classpath is limited only to current directory.

Now, compilation works beautifully.

rustam@rustam-laptop:~/temp/bird_test$ javac Sparrow.java 

This command produces needed .class file. The weird stuff happens when I try to run .class file. The following command works good.

rustam@rustam-laptop:~/temp/bird_test$ java Sparrow

But when I try the following command

rustam@rustam-laptop:~/temp/bird_test$ java ./Sparrow

I receive the following error:

Error: Could not find or load main class ..Sparrow

WTF! i thought that symbol ./ refers to current directory.

Upvotes: 0

Views: 185

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

java takes a class name as argument. It doesn't take a file path. The class name (Sparrow) is then resolved by the java class loader to a .class file based on the classpath, i.e. it looks for a Sparrow.class file in every directory and jar listed in the classpath.

Let's take an example that respects good practices, and thus doesn't use the default package:

package foo.bar;

public class Baz {
    ...
}

The class name of the above class is foo.bar.Baz. To execute it, you must use

java foo.bar.Baz

and java will look for a foo/bar/Baz.class in all the directories listed in the classpath. So if the classpath is set to /hello/world, it will look for the file /hello/world/foo/bar/Baz.class.

Upvotes: 2

Related Questions