1

I have the following simplified file structure:

C:/red/green/black/yellow/white/pink. I am now in cmd in folder 'black'.

The Hello.javafile 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?

2
  • 3
    You compile source files by giving the path to the file, not the package name. Commented Feb 25, 2017 at 18:39
  • @Dave Newton, So is this correct: When compiling a .java file you can be located in cmd in any folder on your computer, while when running the .class file using .packagename.ClassName command you need to be located in a folder prior to the first one of the packagename? Commented Feb 25, 2017 at 18:51

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.