Packages and the Java API
How Java packages organize classes, control visibility, and how to use the Java API (common packages, imports, and classpath) for building modular, reusable code.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Packages organize code into namespaces, avoid name clashes, control accessibility, and determine how the compiler and runtime locate classes on the classpath; understanding them is essential for building, running, and using the Java API correctly.
Key ideas
Fully qualified name (definition): The fully qualified name of a type is the package name followed by the type name, separated by dots, for example
java.util.ArrayList. Use a fully qualified name when you want to refer to a type without animportstatement. For nested types, useOuter.Inner(for example,java.util.Map.Entry).Import statement (definition): An
importdeclaration allows you to use the simple name of a type or static member instead of its fully qualified name. Syntax:import packagename.TypeName;orimport packagename.*;(the latter imports all types in the package, not subpackages).importdoes not copy code; it only provides a name shortcut. Note:java.lang.*is implicitly imported, and types in the same package are always accessible without animport.Static import (definition):
import static packagename.TypeName.memberName;orimport static packagename.TypeName.*;lets you use static members (fields or methods) without qualifying them with the class name.Access levels (definitions and exact statements): Java defines four accessibility levels for members and types. For a member or top-level type T in package P:
- public: Accessible from any other class in any package.
- protected (members only): Accessible in the same package and in subclasses (even if subclasses are in different packages). For top-level types,
protectedis not allowed. - (default) package-private: If no access modifier is given, the member/type is accessible only to other types in the same package.
- private: Accessible only within the top-level class or interface that encloses it (including its nested types).
These are exact visibility rules as per the Java Language Specification. Assumption: accessibility interacts with inheritance rules as defined; note
protectedallows package access plus subclass access (including via inheritance or qualified reference in subclass). In a different package, a subclass can access a protected member only through a reference whose compile-time type is the subclass itself (or one of its subclasses), not through arbitrary superclass instances.Source file layout and directory structure (rule and derivation): The package name determines the directory hierarchy where the
.classfiles (and conventionally source.javafiles) are placed. For example,package com.example.utils;implies the compiled class should be found incom/example/utils/relative to a classpath root. To compile and run, set classpath to the root directory abovecom/. A compilation unit may declare at most one public top-level class or interface, and its name must exactly match the.javafilename.Derivation (what exam answers expect): show the package
p.q.rcorresponds to file pathp/q/r. Explain that the JVM class loader uses classpath entries (directories or JAR files) to locate classes by converting dots to slashes.JAR files and classpath (definition and usage): A JAR (Java ARchive) is a zip-format bundle of compiled classes and resources. The classpath tells the Java compiler and runtime where to find classes and JARs. You can place JARs on the classpath or use the
--module-pathfor Java modules (Java 9+). Assumption: modules introduce a different system (module-info.java) not covered in detail here.Java API (definition): The Java API refers to the standard library packages bundled with the JDK/JRE (for example
java.lang,java.util,java.io,java.net,java.math,java.nio, etc.). The API is documented in Javadoc form and is the canonical reference for method signatures, checked exceptions, and behavior.Naming conventions: Packages normally follow reversed domain names (e.g.,
org.company.project) in lower case. Class names should be UpperCamelCase. These are conventions, not enforced by the compiler, but expected in exams and real projects.
Formulas
- Syntax:
import java.util.*;— imports all types injava.util(not subpackages). - Syntax:
import static java.lang.Math.PI;— imports a static member. - Compile command example:
javac -d . src/com/example/app/Main.java—-d .writes class files to current directory preserving package folders. - Run command example:
java com.example.app.Main— run classMainusing its fully qualified name; the current directory (or specified classpath) must be a classpath root. - Create JAR:
jar cfm app.jar MANIFEST.MF -C classes/ .— create run-able jar (manifest must specifyMain-Class: com.example.app.Main).
Worked examples
Example 1 — Two classes in two packages (compile and run)
- Files and content (two files). Directory layout: project/src/com/example/math/Adder.java and project/src/com/example/app/Main.java
File: project/src/com/example/math/Adder.java
package com.example.math;
public class Adder {
public static int add(int a, int b) { return a + b; }
}
File: project/src/com/example/app/Main.java
package com.example.app;
import com.example.math.Adder;
public class Main {
public static void main(String[] args) {
int s = Adder.add(3, 4);
System.out.println("Sum: " + s);
}
}
Commands (run from project/src):
javac -d ../classes com/example/math/Adder.java com/example/app/Main.javacd ../classesjava com.example.app.MainOutput:
Sum: 7
(This shows package declaration, import and using class across packages.)
Example 2 — Using Java API and static import File: project/src/com/example/app/MathDemo.java
package com.example.app;
import static java.lang.Math.*;
public class MathDemo {
public static void main(String[] args) {
double r = sqrt(2.0); // uses static import
double p = pow(2, 3);
System.out.printf("sqrt(2)=%.6f, 2^3=%.0f\n", r, p);
}
}
Commands:
javac -d ../classes com/example/app/MathDemo.javacd ../classesjava com.example.app.MathDemoOutput:
sqrt(2)=1.414214, 2^3=8
(This shows using standard Java API java.lang.Math and static import.)
Example 3 — Default/package-private visibility (same-package access) File: project/src/com/example/pack/A.java
package com.example.pack;
class A { // package-private class
int value = 10; // package-private field
}
File: project/src/com/example/pack/B.java
package com.example.pack;
public class B { // public class
public static void main(String[] args) {
A a = new A();
System.out.println("Value: " + a.value);
}
}
Commands:
javac -d ../classes com/example/pack/A.java com/example/pack/B.javacd ../classesjava com.example.pack.BOutput:
Value: 10
Note: If class A were moved to another package, the code would fail to compile because A and value are package-private. This is a common exam point about visibility.
Common mistakes
- Expecting
import pack.*;to import subpackages — it does not. - Confusing
importwith including or copying code;importis only a naming convenience. - Forgetting to add classpath or using wrong
-doption — runtimeNoClassDefFoundErrororClassNotFoundException. - Using default (no) package for public APIs — bad practice and can cause build problems; exams often expect using named packages.
- Assuming
protectedgives public access — it allows package access and subclass access only. - Relying on the
javacommand without setting the classpath root correctly — must run using fully qualified name and correct root.
For your exam
- For definitions: the exact definition (bold term), one-line precise rule (for example: "
packagemust be the first non-comment line"), and a short example. - For programs: correct package declarations, matching directory path, compile/run commands, and sample run output.
- For visibility questions: list all four access levels, exact scope of each, and an example showing the boundary (e.g., package-private not visible across packages).
- For API questions: name the package (e.g.,
java.util), list the class used (e.g.,ArrayList), show method signature and a one-line example usage.
Quick check
- Where must the
packagestatement appear in a Java source file? - Does
import java.util.*;import subpackages such asjava.util.concurrent? - Which access modifier allows access to a member from any package?
Answers: 1) As the first non-comment, non-blank line of the source file. 2) No — it imports only types in java.util, not subpackages. 3) public.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?