Sub topic 13
Why to avoid the default package
This chapter assumes you can compile and run a class with javac and java. It also assumes you know what a package declaration does, how source directories mirror packages, and how import works. The default package is the one you get when you leave out the package line. It works for a first program, but it causes problems in real projects, and this chapter explains which ones and how to leave it.
What the default package is
A source file with no package declaration puts its classes in the unnamed package, usually called the default package. The compiler accepts this, and a program like the following runs fine:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello");
}
}You compile it with javac Hello.java and run it with java Hello. There is no package prefix because the class has no package.
The language specification describes the unnamed package as a convenience for small or temporary programs and for starting development. It is not meant for production code. The sections below show the concrete reasons.
Named packages cannot see it
This is the main problem. Code in the default package can use classes from named packages. Code in a named package cannot refer to a class in the default package, because there is no name to write.
Suppose src/Utils.java has no package:
public class Utils {
public static String shout(String s) {
return s.toUpperCase() + "!";
}
}Now src/com/example/app/App.java tries to use it:
package com.example.app;
public class App {
public static void main(String[] args) {
System.out.println(Utils.shout("hello"));
}
}Compiling both files fails:
javac -d out src/Utils.java src/com/example/app/App.javaThe compiler reports cannot find symbol for Utils. The simple name Utils is looked up in the current package (com.example.app), in the imports, and in java.lang. The unnamed package is in none of those places.
Importing does not help. A single-type import needs a qualified name, and the unnamed package has no qualifier, so import Utils; fails with an error such as '.' expected. Since Java 1.4 the language has deliberately closed this gap.
The result is a one-way dependency. Every class in a library, framework, or shared module has to be in a named package, or nobody else can call it. A default-package class can only be a leaf: an entry point or a throwaway test.
Fixing it: move the class into a package
The fix has three parts. Add the declaration, move the file to the matching directory, and import the class where it is used.
src/com/example/util/Utils.java:
package com.example.util;
public class Utils {
public static String shout(String s) {
return s.toUpperCase() + "!";
}
}src/com/example/app/App.java:
package com.example.app;
import com.example.util.Utils;
public class App {
public static void main(String[] args) {
System.out.println(Utils.shout("hello"));
}
}javac -d out src/com/example/util/Utils.java src/com/example/app/App.java
java -cp out com.example.app.AppThis prints HELLO!. Delete the old src/Utils.java. If you leave it, a stale default-package copy of Utils stays on the source path and invites confusion.
Any public class that lives in a file with the wrong directory is a separate error. The tools can often find it, but build tools and IDEs will complain. Keep the directory and the package in agreement.
Name collisions on the classpath
Packages exist to give classes qualified names. Without a package, a class has only its simple name, such as Util or Main. Two libraries that both ship a default-package Util clash.
When the JVM needs Util, it asks the class loader, which searches the classpath entries in order and takes the first match:
java -cp a.jar:b.jar MainIf both a.jar and b.jar contain Util.class at their root, every reference to Util resolves to the one in a.jar. Nothing warns you. Swapping the order silently changes behavior. With com.acme.a.Util and com.acme.b.Util, both versions load side by side.
A related effect concerns access. All default-package classes loaded by the same class loader belong to one runtime package. Package-private members of unrelated classes are therefore visible to each other, even if they came from different directories or jars. That undoes the encapsulation described in the chapter on package-private and protected access.
Frameworks and tools
Several common tools assume named packages.
| Tool or feature | What goes wrong in the default package |
|---|---|
| Named modules (`module-info.java`) | A module cannot contain the unnamed package. `javac` rejects it with "unnamed package is not allowed in named modules". |
| Spring Boot component scanning | Scanning starts at the main class's package. In the default package that means the whole classpath, and Spring logs a warning that the context is unlikely to start. |
| Other annotation or classpath scanners | They filter by package prefix. An empty prefix matches everything. |
| Shared libraries | Callers in named packages cannot use them at all. |
| Reflection | `Class.forName("Utils")` works, but you must pass a string and cannot name the type in code. |
The module case deserves a closer look, because it is a hard failure. Consider a project with this descriptor:
module com.example.app {
}If any source file in the same module has no package line, compilation stops. You cannot migrate to modules without first moving every class into a package.
Detecting the default package at runtime
You can see the difference with getPackageName(), which was added in Java 9:
public class Probe {
public static void main(String[] args) {
System.out.println("[" + Probe.class.getPackageName() + "]");
System.out.println("[" + String.class.getPackageName() + "]");
}
}This prints [] for Probe and [java.lang] for String. An empty string means the class is in the unnamed package. You can use this in a quick check that logs a warning when a class ends up in the default package.
When the default package is acceptable
Some uses are fine:
- A single-file experiment, such as a class you write to test a language feature.
- A learning exercise, as in the early chapters of this tutorial.
- A script run directly with the source launcher, as in
java Hello.java(Java 11 and later).
The common thread is that nothing else depends on the code and it will not become a library. If either assumption changes, add a package. Moving a class later is cheap in an IDE, which updates the declaration, the directory, and the imports in one step. It is cheaper still to start with a package from the first commit.
A short checklist for migration
If you inherit a project with default-package classes, work in this order:
- Pick a base package that follows the reverse-domain convention, such as
com.example.shop. - Move the entry point and the other classes into subpackages by role (
model,util,app). - Add the
packageline to each file and update the directories to match. - Add imports in every class that used a moved class. Former default-package users that you did not move still compile, but named code cannot use them until they move.
- Fix
mainreferences in scripts, manifests, and run configurations. The class is nowcom.example.shop.Main, notMain. - Rebuild from a clean output directory so no old
.classfiles remain at the root.
Exercise
A teammate puts Config.java in src/ with no package line. Your class com.example.app.Server calls Config.load(). Why does compilation fail, and would import Config; fix it?
Show answer
The simple name Config is looked up in com.example.app, in the imports, and in java.lang. The unnamed package is not searched from a named package, so the compiler reports cannot find symbol. import Config; does not fix it, because a single-type import must be a qualified name and the unnamed package has no qualifier. The compiler rejects it with a syntax error. The fix is to give Config a package, move it to the matching directory, and import it by its qualified name.
Exercise
Two jars on the classpath, a.jar and b.jar, each contain a root-level Util.class with different code. You run java -cp b.jar:a.jar Main. Which Util does Main get, and how would packages have avoided the problem?
Show answer
It gets the one from b.jar, because the class loader takes the first match in classpath order and gives no warning. If each jar used a package, such as com.acme.a.Util and com.acme.b.Util, the qualified names would differ and both classes could be loaded.
Exercise
A project adds module-info.java and fails to compile with "unnamed package is not allowed in named modules". What is the cause, and what is the minimum change that fixes it?
Show answer
At least one source file in the module has no package declaration, so its class is in the unnamed package, which a named module cannot contain. Add a package declaration to each such file and move it into the matching directory, then update imports and any main class references.