Package name is different than the folder structure but still Java code compiles

whitehat picture whitehat · Dec 6, 2011 · Viewed 15.8k times · Source

I am using Notepad++ to write my Java code and Command Prompt to compile and run it. Following is my sample Java code,

    package abraKadabra;

    public class SuperClass{
       protected int anInstance;

       public static void main(String [] abc){
           System.out.println("Hello");
       }
    }

However, this file is in the following folder structure :

"usingprotected\superPkg" (usingProtected is a folder somewhere in the hierarchy in C:)

So, my package name here should be something like usingProtected.superPkg instead of abraKadabra as I wrote it.

But, when I compile this Java code from command prompt, it compiles fine with no error or warnings. Why is it so? Shouldn't the package name adhere to the folder structure? And if it should, how would it adhere?

For e.g. if my package name is usingProtected.superPkg, will the compiler check in the reverse order. The present working directory should be superPkg, then the parent directory should be usingProtected and its done. Is it how it checks the folder structure with package name?

Answer

Jon Skeet picture Jon Skeet · Dec 6, 2011

The Java language specification doesn't force files to be in a certain directory. It optionally allows the compiler to require that public classes are in files with the same name of the class, but I don't think there's anything similar for packages. Section 7.2.1 talks about possible storage options in a file system, but it doesn't say anything about enforcing source code structure, as far as I can see.

However, it's best practice - and a pretty much universally accepted convention - to reflect the package structure in the source directory structure... and javac will use this to try to find source files which aren't explicitly specified to be compiled.

Note that if you're compiling from the command line, by default each class will appear in the same location as the corresponding source file, but if you use the "-d" option (e.g. "-d bin") the compiler will build an appropriate output directory structure for you, rooted in the specified directory.