Reputation: 145
My directory structure looks like this.
PackagesUnit3/com/myname/start/PackagesTest.java
(this class contains my main and the import statement "import com.systems.mui.*;)
PackagesUnit3/com/systems/mui/Test.java
(this class contains the package statement "package com.systems.mui;")
With PackageUnit3 as my base directory I can compile both classes successfully with the statement
"javac com/myname/start/PackagesTest.java"
However I cannot run the code with the command
"java com.myname.start.PackagesTest"
Error: "Exception in thread "main" java.lang.NoClassDefFoundError: com/myname/start/PackagesTest (wrong name: PackagesTest)"
The complier successfully generated .class
files for each of the java classes and placed them in the same location as the source files.
According to Horstmann, "Core Java" 9th ed. p. 186, my "java" command syntax ought to work.
I should not have to specify the current directory (".")because I am not using the classpath (-cp) option.
One note: I used the "SUBST R: " command to establish the PackagesUnit3 directory as the base directory. My actual command line looks like R:>
Any suggestions??
Upvotes: 5
Views: 1302
Reputation: 4041
I've checked on this, recreated the scenario and you're right... Assuming all classes are public, with correct package declarations, and compiling from the root directory, class Test
will compile succesfully since it doesn't references any other classes (or classes from different packages). No -cp
option is required
While compiling class PackagesTest
, it fails to find class Test
. But by adding -cp .
, it compiles succesfully.
Once both files are compiled, trying to run PackagesTest
' main, will also fail to find class Test
. But by adding -cp ,
it runs smoothly.
By using the option -verbose
you can see where is javac (and java) command looking for classes, as it displays the default classpath, which doesn't contains "." (the local directory)
Upvotes: 0
Reputation: 1500385
Given the exception, it looks like you're missing a package
statement:
package com.myname.start;
Your package declaration should match your directory structure, and then the class will be generated with the correct fully-qualified name of com.myname.start.PackageTest
.
Either compile in an IDE which will sort things out for you, or compile from the root of your package structure with an optional -d
argument to specify the root output directory, e.g.
$ javac -d bin com/myname/start/*.java
$ java -cp bin com.myname.start.PackageTest
Upvotes: 10