I was writing some practice programs for my java certification this morning, and noticed that I had mistyped a package name, so it didn't match the subdirectory the java file was in. I compiled the code expecting an error, but everything compiled file -- not even a warning.
I googled around a bit, and most of the pages I read said that the package name had to match the subdirectory. My experience shows that's not the case.
When I attempted to run the program, it didn't work because the .class file was in the wrong directory. I moved it to the correct directory, and got this error:
Exception in thread "main" java.lang.NoClassDefFoundError: com/sample/directory
/doesnt/even/exist/OtherPackageMemberModifiers (wrong name: com/sample/chap01/O
therPackageMemberModifiers)
So what I think I'm seeing is that Java code will compile if the package and the subdirectory don't match up, but there doesn't seem to be a way to run the code if you do that. Is that correct?
The package name has to match the directory name in order for the class file to be found correctly. It doesn't have to match the directory name at compilation time for some compilers (e.g. javac) although others (such as Eclipse) will at least give a warning.
The "way to run the code if you do that" is to create the directory structure and put it in there manually - the class file itself is entirely valid.
Note that if you use the -d
flag, javac will build the appropriate directory hierarchy for you, regardless of source location. For example:
javac -d bin ClassInPackage.java
will create any required directories under bin
to match the package declared in ClassInPackage.java
.
Having said all of thise, I'd still strongly encourage you to make the source directories match the packages, even though you can get away without it :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With