Search code examples
javapackagejavac

Why do I have to be outside the package's folder to properly execute the class file?


(Note: I know I am not using standard naming conventions here. The names are simply for the purpose of simplicity.)

I have a file called 'PackageTest.java'. It's sole purpose is to print a line to the console saying, "This works!". It belongs to a package named main. In my console I execute the command:

javac -d . PackageTest.java

This creates a new directory (folder) called main, which contains the class file named 'PackageTest.main'. I am CD'd into it's parent directory, and I execute the following command:

java main.PackageTest

And the console then reads:

This works!

So the file executed. That's good. Now I CD into the 'main' folder. I execute the command:

java main.PackageTest

Only to get the result:

Error: Could not find or load main class main.PackageTest
Caused by: java.lang.ClassNotFoundException: main.PackageTest

So I try this command:

java PackageTest

And now I get this error:

Error: Could not find or load main class PackageTest
Caused by: java.lang.NoClassDefFoundError: main/PackageTest (wrong name: 
PackageTest)

Why do I have to be outside of the directory to allow the file to execute?


Solution

  • The package (and folder) are semantically meaningful. You can specify the classpath, if you use an absolute path you can move anywhere in your tree and still run the code. It's also possible to use a relative path. Like,

    java -cp .. main.PackageTest