Java Package Access and the Class Path
Understand Java's default package access and why forgetting private breaks encapsulation, then master the class path: how the JVM and javac locate classes in directories and JAR files, -cp and --class-path, wildcards, the CLASSPATH variable, and fixing ClassNotFoundException.
kvi5hnuCode Sprout team member12 min readOn this page
The previous article showed how to name packages and import classes. Two practical questions remain:
- Who may use a class, method or field that's neither
publicnorprivate? That's package access. - Where does Java look for the class files of your packages and libraries? That's the class path.
Both come up constantly in real work. Classpath mistakes are behind most ClassNotFoundException and NoClassDefFoundError messages you'll ever see.
Package Access
You already know two access modifiers:
publicfeatures can be used by any class.privatefeatures can be used only by the class that declares them.
If you write neither, the feature (class, method or field) has package access, also called package-private or default access. It can be used by all code in the same package, and by nothing outside it.
package com.a;
public class Counter {
int count; // package access: any class in com.a can read and change it
private int secret; // only Counter
public int value() { return count; }
}
class Helper { } // package access: only visible inside com.a
Code in another package gets compile errors:
package com.b;
import com.a.Counter;
public class Other {
void f(Counter c) { c.count++; } // error: count is not public in Counter; cannot be accessed from outside package
void g() { new com.a.Helper(); } // error: Helper is not public in com.a; cannot be accessed from outside package
}
| Modifier | Same class | Same package | Subclass in other package | Everywhere |
|---|---|---|---|---|
public | ✓ | ✓ | ✓ | ✓ |
protected | ✓ | ✓ | ✓ (with restrictions) | ✗ |
| (none): package access | ✓ | ✓ | ✗ | ✗ |
private | ✓ | ✗ | ✗ | ✗ |
(protected is covered with inheritance in the next part.)
Package access for classes: a sensible default
Recall the staff program from article 30 (StaffDemo). Its Employee class wasn't declared public, so only classes in the same package (the unnamed package, there) could use it. For classes, package access is a reasonable default: helper classes that support a package's public API shouldn't be visible to the whole world.
Package access for fields: an unfortunate default
For fields, package access is a poor default. Fields must be explicitly marked private, and it's very easy to forget the keyword. A forgotten private silently opens the field to every class in the package, which breaks encapsulation.
Picture a class written in a hurry:
package com.example.billing;
public class Invoice {
private long id;
double total; // forgot private: every class in com.example.billing can now change it
. . .
}
Nothing warns you. Any class in com.example.billing can now write invoice.total = 0; and bypass every check in Invoice's methods. Even the JDK has such fields: run javap -p java.awt.Window on JDK 25 and you'll see package-private fields like int state; that every class in java.awt can touch.
Packages aren't sealed by default
Package access has a weakness: by default, packages are open. Anyone can add classes to a package by writing the same package declaration. In early versions of Java, it was easy to smuggle a class into java.awt: start the file with package java.awt;, place the class file in a java/awt directory on the class path, and you had access to java.awt's package-private internals. Attackers used this trick to reach internals that were never meant to be public.
The JDK closed this hole for its own packages:
-
Since Java 1.2, the class loader refuses user classes in packages whose names start with
java.:textException in thread "main" java.lang.SecurityException: Prohibited package name: java.foo -
Since Java 9, the JDK's packages live in modules, and the compiler rejects
package java.awt;outright:error: package exists in another module: java.desktop.
Your own packages don't get this protection automatically. An older mechanism let JAR files declare packages sealed (Sealed: true in the manifest), preventing classes from other JARs from joining them; it's now obsolete. Today, use modules to encapsulate packages: a module decides which packages it exports, and code outside can't access the rest at all. Modules are covered in the last part of this course.
The Class Path
Class files live in directories that match their packages, as you saw in the previous article. They can also be stored in JAR (Java ARchive) files: a single compressed file containing many class files and their subdirectories. When you use a third-party library, you usually get it as one or more JAR files. (The next article shows how to create your own.)
To share classes among programs:
- Put your class files inside a directory, say
/home/dev/build/classes. This is the base directory of the package tree: the classcom.example.payroll.Employeemust be in/home/dev/build/classes/com/example/payroll/Employee.class. - Put JAR files in a directory, say
/home/dev/libs. - Set the class path: the list of all locations that can contain class files.
The entries are separated by colons on Linux and macOS, and by semicolons on Windows:
/home/dev/build/classes:.:/home/dev/libs/helpers.jar (Linux, macOS)
c:\build\classes;.;c:\libs\helpers.jar (Windows)
In both cases, the period denotes the current directory. So this class path contains:
- the base directory
/home/dev/build/classes(orc:\build\classes), - the current directory
., and - the JAR file
/home/dev/libs/helpers.jar(orc:\libs\helpers.jar).
You can include all JAR files of a directory with a wildcard:
/home/dev/build/classes:.:/home/dev/libs/'*' (Linux, macOS: quote * so the shell doesn't expand it)
c:\build\classes;.;c:\libs\* (Windows)
The wildcard picks up .jar (and .JAR) files only, not .class files or subdirectories.
The Java platform classes (java.lang, java.util, …) are always found. Don't put them on the class path.
How the virtual machine searches
The class path lists the starting points for locating classes. Suppose the JVM needs com.example.payroll.Employee with the class path /home/dev/build/classes:.:/home/dev/libs/helpers.jar:

- It first looks in the Java platform classes and doesn't find it there.
- Then it tries each class path entry in order:
/home/dev/build/classes/com/example/payroll/Employee.classcom/example/payroll/Employee.classrelative to the current directorycom/example/payroll/Employee.classinside/home/dev/libs/helpers.jar
- The first match wins. If nothing matches, you get
ClassNotFoundException(when loading the main class or loading by name) orNoClassDefFoundError(when a class that existed at compile time is missing at run time).
Because the first match wins, two JARs containing different versions of the same class can cause confusing behavior. This is known as "JAR hell", and it's one of the problems build tools and modules help with. To see exactly where each class comes from, run with -verbose:class:
$ java -verbose:class -cp ../lib/greeter.jar:. App | grep Greeter
[0.015s][info][class,load] com.example.Greeter source: file:/.../lib/greeter.jar
How the compiler searches
The compiler has a harder job, because source code often uses simple names like Employee instead of full names. It must first figure out which package a class belongs to, using the import declarations. Suppose a file contains
import java.util.*;
import com.example.payroll.*;
and uses Employee. The compiler resolves the simple name in this order:
- a single-type import such as
import com.example.payroll.Employee;(none here), - a class
Employeein the current package, - only then the on-demand imports:
java.lang.*(always imported),java.util.*andcom.example.payroll.*.
The first two win outright: a current-package Employee silently shadows any Employee from a * import, with no error. Only if the name comes from the on-demand imports does the compiler check all of them, searching each in every class path location; if more than one on-demand package supplies Employee, that's a compile-time error (an ambiguous reference), which you fix with a single-type import. Since fully qualified names are unique, the order of import declarations doesn't matter.
The compiler goes a step further: it also looks for source files. If a source file is newer than its class file, the compiler recompiles it automatically. Finding sources is easy for public classes from other packages: a file can contain only one public class, and the file must be named after it. Non-public classes of the current package may live in files with different names, so the compiler searches all source files of the current package for them.
Setting the Class Path
IDEs and build tools manage the class path for you, but you should know how to set it by hand. That's the only way to troubleshoot configuration problems.
The -cp option (preferred)
Pass it to java (and javac) with -classpath, its short form -cp, or the modern long form --class-path:
java -classpath /home/dev/build/classes:.:/home/dev/libs/helpers.jar MyProg
java -cp c:\build\classes;.;c:\libs\helpers.jar MyProg
java --class-path ../build/classes:. App
The whole command goes on one line. Long class paths are best kept in a shell script, a batch file, or an argument file: put the options in a text file and pass @filename (javac has always supported this; the java launcher has since Java 9):
# file: app.args
--class-path lib/a.jar:lib/b.jar:lib/c.jar:classes
java @app.args com.example.Main
The CLASSPATH environment variable
Alternatively, set the CLASSPATH environment variable. It applies to all java and javac commands in that shell unless a -cp option overrides it:
export CLASSPATH=/home/dev/build/classes:.:/home/dev/libs/helpers.jar # bash, zsh
set CLASSPATH=c:\build\classes;.;c:\libs\helpers.jar # Windows cmd
$env:CLASSPATH = "c:\build\classes;.;c:\libs\helpers.jar" # PowerShell
It stays set until the shell exits.
In practice: build tools
In professional projects, you rarely type class paths. Maven and Gradle download your dependencies (and their dependencies) and build the class path for compiling, testing and running. Your IDE does the same. Useful commands when something goes wrong:
| Task | Command |
|---|---|
| See Maven's dependency tree | mvn dependency:tree |
| See Gradle's runtime class path | gradle dependencies --configuration runtimeClasspath |
| Print the class path Maven builds | mvn dependency:build-classpath |
| Find which JAR a class is loaded from | java -verbose:class ... |
| Analyze dependencies of class files and JARs | jdeps -cp lib/* app.jar |
Common questions
What's the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when code asks for a class by name at runtime (for example Class.forName, or the launcher looking for your main class) and it isn't found. NoClassDefFoundError means that a class was available when the code was compiled but is missing at runtime, or that its static initialisation failed earlier. Both usually point to a class-path problem.
Is package access the same as protected?
No. Package access allows only classes in the same package. protected allows the same package plus subclasses in other packages. The next part covers protected in detail.
Is the class path still relevant with modules?
Yes. Most applications still run on the class path, and modular and non-modular code can be mixed (non-modular JARs on the class path end up in the "unnamed module"). Build tools hide the details, but knowing how the class path works helps when diagnosing NoClassDefFoundError and duplicate-class problems.
How do I find which JAR a class is loaded from?
Run with -verbose:class (or -Xlog:class+load) and search for the class name, or print MyClass.class.getProtectionDomain().getCodeSource().getLocation(). Maven's dependency:tree and Gradle's dependencies task show which library brought a JAR in.
Should test classes be in the same package as the classes they test?
Commonly, yes. With the standard Maven/Gradle layout, src/test/java/com/example/FooTest.java is in the same package as src/main/java/com/example/Foo.java, so tests can use package-private helpers without making them public.
Summary
- Features without
public,protectedorprivatehave package access: visible to all code in the same package. - Package access suits helper classes, but for fields it's a trap. Always write
privateexplicitly. - Packages are open by default; the JDK forbids user classes in
java.*. Use modules to truly encapsulate packages. - The class path lists directories (package base directories) and JAR files, separated by
:(Unix) or;(Windows).dir/*adds all JARs in a directory. - The JVM searches platform classes first, then the class path entries in order. The first match wins.
- If you set a class path, include
.when your classes are in the current directory. - Prefer
-cp/--class-path(or@argfiles) over theCLASSPATHvariable, and never setCLASSPATHpermanently.
Practice Questions
Class Account in package bank declares double balance; (no modifier). Can class bank.Audit read it? Can class reports.Monthly?
bank.Audit can, because it's in the same package. reports.Monthly can't: package access stops at the package boundary (compile error "balance is not public in Account; cannot be accessed from outside package").
You compile with javac -cp lib/json.jar Main.java and run java -cp lib/json.jar Main. You get "Could not find or load main class Main". Why?
Setting the class path replaces the default (.), so the current directory, where Main.class lives, isn't searched. Use java -cp lib/json.jar:. Main (with ; on Windows). The compile only worked because Main.java was named on the command line; if Main used another class from the current directory, javac would fail too, for the same reason.
What does the class path entry libs/* include? Does it include libs/util/x.jar or libs/Foo.class?
All .jar files directly in libs. It doesn't include JARs in subdirectories (libs/util/x.jar) or loose class files (libs/Foo.class). For those, add libs/util/* or libs itself as entries.
Two JARs on the class path both contain com.acme.Parser, in different versions. Which one is used?
The one in the JAR listed first on the class path. The JVM takes the first match. This "JAR hell" situation causes subtle bugs. Use -verbose:class to diagnose it, and resolve the conflict in your build tool.
Why is setting CLASSPATH in your shell profile a bad idea?
It silently affects every Java program you run, you forget it's there, and it may lack . or contain stale JARs, leading to "compiles but doesn't run" and wrong-version problems. Pass -cp per command or let the build tool manage it.
What's the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when code (or the launcher, for the main class) asks to load a class by name and it isn't found. NoClassDefFoundError is an error thrown when a class that was present at compile time can't be found when the running code first uses it, typically a JAR missing from the runtime class path.
Previous: Java Packages: Package Names, Imports and Static Imports
Next: Java JAR Files: Creating, Running and Configuring with the Manifest
Related reading
- Your First Java Program Explained: Classes, main, Statements and Comments
- Java Packages: Package Names, Imports and Static Imports
- Java Records: Compact Data Classes with Canonical and Compact Constructors
- Java static Fields and Methods: Class Variables, Constants, Factory Methods and main
- Defining Your Own Classes in Java: Fields, Constructors and Methods

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.