Why do java source files require package declarations?

As you (implicitly) acknowledged, you are not required to declare the name of a package in the case of the default package. Let us put that quibble aside …

The reason for this seeming redundancy is that without a package declaration, the meaning of Java1 source code would be ambiguous. For example, a source file whose pathname was “/home/steve/project/src/com/example/Main.java” could have 7 different fully qualified names, depending on how you compiled the code. Most likely, only one of those will be the “correct” one. But you wouldn’t be able to tell which FQN is correct by looking at (just) the one source file.


It should also be noted that the Java language specification does not require you to organize the source code tree according to the packages. That is a requirement of a (large) family of Java compilers, but a conformant compiler could be written that did not require this. For example:

  • The source code could be held in a database.
  • The source code could be held in a file tree with random file names2.

In such eventualities, the package declaration would not be duplicative of file pathnames, or (necessarily) of anything. However, unless there was some redundancy, finding the correct source “file” for a class would be expensive for the compiler … and problematic for the programmer.

Considerations like the above are the practical reason that most Java tool chains rely on file tree structure to locate source and compiled classes.


1 – By this, I mean hypothetical dialect of Java which didn’t require package declarations.
2 – The compiler would need to scan the file tree to find all Java files, and parse them to work out which file defined which class. Possible, but not very practical.

Leave a Comment