Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
How Java packages and imports work for the OCP 21 exam: wildcards, java.lang, redundant imports, Date naming conflicts, fully qualified names, javac -d, the three class path options, JAR files, element order in a file and Java 25 module imports.
kvi5hnuCode Sprout team member14 min readOn this page
The JDK ships with thousands of classes, and your own projects add more. Packages keep them organized and let two classes share a simple name, such as java.util.Date and java.sql.Date. Imports tell the compiler which packages to search. The exam asks about this in two ways: questions about which import lines compile, and questions about whether a javac or java command line works. This article covers both and then explains the order of the parts of a source file.
Packages
A package is a named group of related types. Its name is written in parts separated by dots, and the parts go from general to specific:
- Names starting with
javaorjavaxcome with the JDK. You may not declare your own classes in ajava.*package; the class loader refuses to load them. - Other code usually starts with a domain name written backwards. Code from an organization that owns
example.commight live incom.example.inventory. - A longer name such as
com.example.inventory.reportis called a child package ofcom.example.inventory. The name is the only connection between them. To the compiler they are two unrelated packages, and that matters for wildcards.
Each part of a package name follows the same rules as a variable name (letters, digits, _ and $, not starting with a digit, not a keyword). The exam uses short names such as a.b.c to save space, and it doesn't try to trick you with invalid package names.
The package declaration at the top of a file puts every type in that file into the package:
package com.example.inventory;
A file without a package declaration is in the default package (the unnamed package). Exam listings use it constantly to keep code short. Real projects shouldn't, because a class in the default package can't be imported into any named package. There is no name to write after import.
Imports
You can always refer to a class by its fully qualified name, the package plus the class name, such as java.util.Random. An import lets you write the simple name Random instead:
import java.util.Random; // single-type import
public class Dice {
public static void main(String[] args) {
Random dice = new Random();
System.out.println(dice.nextInt(6) + 1); // 1 to 6
}
}
Without the import, the compiler reports cannot find symbol at Random. The same message appears when you misspell a name, so when you see it on the exam, check both possibilities.
An import doesn't copy any code into your class and doesn't make the program slower or larger. It only tells the compiler how to expand a simple name into a fully qualified one. The bytecode always contains the full name.
Wildcard imports
An on-demand import (a wildcard import) ends with .* and makes every type directly inside one package available:
import java.util.*; // Random, List, Map, Scanner, ...
Three limits apply:
- No child packages.
java.util.*does not reachjava.util.concurrent.atomic.AtomicInteger. For that you needimport java.util.concurrent.atomic.*;orimport java.util.concurrent.atomic.AtomicInteger;. - Only one
*, only at the end.import java.*.*;andimport java.util.*.List;don't compile. - Types only, never methods or fields. Importing static members is a different feature,
import static, covered in the methods chapter.
The third point has a subtle twist. After a wildcard you may name a type instead of a package, as in import java.util.Map.*;. This compiles and imports the types nested inside Map, so you can write Entry instead of Map.Entry. It doesn't import methods. import java.nio.file.Paths.*; also compiles, but Paths has no nested types, so it imports nothing, and a bare call like get("x") fails with cannot find symbol. Some study material says this line doesn't compile. It does; it's just useless.
You don't need a separate import for a nested type at all. With import java.util.*; you can write Map.Entry<String, Integer>, because Map is imported and Entry is reached through it.
Wildcards versus explicit imports is a matter of style. Explicit imports document exactly which classes a file uses. Wildcards keep the list short. Both appear on the exam, and neither affects runtime speed.
What you never need to import
Two kinds of import are redundant. They compile, but removing them changes nothing:
- Anything from
java.lang, which every file imports automatically. That's whyString,System,Math,IntegerandObjectwork without an import. - Anything from the same package as the current file. The compiler always looks there.
An import is also redundant when another import already covers the same class. Count the redundant lines here:
import java.lang.Math; // 1
import java.lang.*; // 2
import java.util.Scanner; // 3
import java.util.*; // 4
public class Calc {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(Math.abs(-4));
}
}
Lines 1 and 2 are redundant because of java.lang. Line 4 is redundant because line 3 already supplies Scanner and the class uses nothing else from java.util. If line 3 were deleted, line 4 would stop being redundant. Repeating exactly the same import twice is also redundant, and it compiles.
Naming conflicts
Two classes in different packages can share a simple name. The classic example on the exam is Date, which exists as java.util.Date and java.sql.Date. The resolution rules are:
| Imports | Using Date |
|---|---|
import java.util.*; only | java.util.Date |
import java.util.*; and import java.sql.*; | Does not compile: reference to Date is ambiguous |
import java.util.Date; and import java.sql.*; | java.util.Date. An explicit import beats any wildcard. |
import java.util.Date; and import java.sql.Date; | Does not compile, even if Date is never used |
Two details make the difference on tricky questions:
- With two wildcards, the error appears only where
Dateis actually used. If the class never mentionsDate,import java.util.*; import java.sql.*;compiles fine. - With two single-type imports of the same simple name, the error is reported on the second import line (
a type with the same simple name is already defined by the single-type-import of Date), whether or notDateis ever used.
A single-type import also conflicts with a top-level class declared in the same file. If a file says import java.util.Date; and also declares class Date { }, it doesn't compile.
When you really need both classes, import one of them and write the other with its fully qualified name, or import neither:
import java.util.Date;
public class Report {
Date created; // java.util.Date
java.sql.Date dueDate; // the fully qualified name always works
}
A fully qualified name never needs an import and is never ambiguous.
Compiling and running code in packages
Packages map onto directories. A class declared in package store.model; must be in a directory path ending in store/model, and its compiled .class file must sit in a matching directory under one of the class path roots.

Here are two classes in that layout, starting from a working directory that contains store/:
package store.model;
public class Product {
private final String name;
private final int cents;
public Product(String name, int cents) {
this.name = name;
this.cents = cents;
}
public String label() {
return name + " @ " + cents / 100 + "." + String.format("%02d", cents % 100);
}
}
package store.app;
import store.model.Product;
public class Main {
public static void main(String[] args) {
Product p = new Product("Tea", 349);
System.out.println(p.label());
}
}
Compiling
javac takes file paths, so you write slashes and the .java extension:
javac store/model/Product.java store/app/Main.java
By default each .class file is written next to its source file. A shell wildcard can pick up every source file in one directory, as in javac store/app/*.java, but it doesn't descend into subdirectories. javac *.java run from the top directory finds nothing in store/.
The -d option names a separate output directory, and javac re-creates the package directories under it:
javac -d classes store/model/Product.java store/app/Main.java
That command creates classes/store/model/Product.class and classes/store/app/Main.class. Options are case-sensitive: -d is the output directory, and -D is not a javac option.
Running
java takes a fully qualified class name: dots, no .class extension. It also needs to know where packages start. That's the class path, given with any of three equivalent options:
java -cp classes store.app.Main
java -classpath classes store.app.Main
java --class-path classes store.app.Main
Each prints Tea @ 3.49. The single-dash forms are -cp and -classpath. The long form has two dashes, --class-path. A wrong number of dashes is an error. javac accepts the same three options when the code being compiled needs classes from elsewhere.
These fail, and the exam likes to show them:
| Command | Why it fails |
|---|---|
java -cp classes Main | The class is store.app.Main. The simple name isn't enough. |
java store.app.Main (from the source directory, compiled with -d classes) | The default class path is the current directory, and the class files are under classes/. |
java -cp classes store/app/Main.class | That's a file name, not a class name. |
java -cp classes/store/app Main | The class path must point at the directory where the package starts, not where the class file is. |
A class path can list several entries. On macOS and Linux they're separated by : and on Windows by ;:
java -cp "classes:lib/util.jar" store.app.Main # macOS / Linux
java -cp "classes;lib\util.jar" store.app.Main # Windows
An entry can be a directory (a root of the package tree) or a JAR file. The special entry lib/* means every .jar file in lib; it doesn't mean the directory itself, and it doesn't include subdirectories. Quote it so the shell doesn't expand it. If you give -cp twice, only the last one counts. If you leave it out, the class path is the CLASSPATH environment variable, or . when that isn't set.
JAR files
A JAR (Java archive) is a ZIP file of class files and resources with a META-INF/MANIFEST.MF entry. You create one with the jar tool:
jar -cvf store.jar -C classes . # create, verbose, file name; -C changes into classes first
jar cf store.jar -C classes . # same thing, old-style option letters, quiet
java -cp store.jar store.app.Main # a JAR on the class path works like a directory
jar option | Meaning |
|---|---|
-c / --create | Create a new archive |
-v / --verbose | List what is added |
-f / --file | The archive's file name |
-C dir | Change to dir before adding the files that follow |
-e / --main-class | Record an entry point in the manifest |
With an entry point recorded (jar cfe app.jar store.app.Main -C classes .), java -jar app.jar runs the program without a class name. java -jar ignores -cp; the JAR's manifest controls its class path.
The order of elements in a file
Comments and blank lines can go anywhere. Everything else follows a fixed order, often remembered as PIC (package, import, class):
| Element | Example | Required? | Position |
|---|---|---|---|
| Package declaration | package store.app; | No | First, before everything except comments |
| Imports | import java.util.*; | No | After the package, before any type |
| Type declarations | public class Main { } | Yes, in practice | After the imports |
| Fields and methods | int count; void run() { } | No | Inside a type, in any order, and they can be mixed |
So this is fine, because comments may come before package:
// Inventory application, version 2
package store.app;
import java.util.List;
public class Shelf {
void stock() { }
List<String> items; // fields can come after methods
}
And each of these is a compile error:
import java.util.*;
package store.app; // DOES NOT COMPILE: package must come first
package store.app;
class Helper { }
import java.io.*; // DOES NOT COMPILE: imports can't follow a type
package store.app;
String name; // DOES NOT COMPILE in Java 21: a field must be inside a class
public class Shelf { }
A file can have at most one package declaration, so every type in a file is in the same package.
What's current
- Java 25 finalized module import declarations (
import module java.sql;, JEP 511). They're on the Java 25 exam, not on 1Z0-830. - Single-type, on-demand (
*) and static imports and the class path options work the same in Java 21 and 25.
Exam traps from this article
A complete example
This program shows the conflict rules in action. java.util.* brings in List and Map, the explicit import picks java.sql.Date over the wildcard, and the other Date is used through its fully qualified name.
import java.util.*; // wildcard: every class directly in java.util
import java.sql.Date; // single-type import beats the wildcard for "Date"
import java.util.concurrent.atomic.AtomicInteger; // child packages need their own import
public class Solution {
public static void main(String[] args) {
// "Date" now means java.sql.Date, because the explicit import wins.
Date launch = Date.valueOf("2024-03-19");
System.out.println("Date resolves to " + Date.class.getName());
// The other Date is still usable through its fully qualified name.
java.util.Date sameInstant = new java.util.Date(launch.getTime());
System.out.println("Other Date is " + sameInstant.getClass().getName());
System.out.println("Same millis? " + (sameInstant.getTime() == launch.getTime()));
System.out.println("java.sql.Date text " + launch);
// List and Map come from the java.util wildcard; Map.Entry is reached through Map.
List<String> pkgs = new ArrayList<>(List.of("java.util", "java.sql"));
Map<String, Integer> sizes = new TreeMap<>();
for (String p : pkgs) {
sizes.put(p, p.length());
}
for (Map.Entry<String, Integer> e : sizes.entrySet()) {
System.out.println(e.getKey() + " has " + e.getValue() + " characters");
}
// AtomicInteger needed its own import: java.util.* does not reach child packages.
AtomicInteger counter = new AtomicInteger();
pkgs.forEach(p -> counter.incrementAndGet());
System.out.println("Imported packages " + counter.get());
// String, Math and System live in java.lang, which is imported automatically.
System.out.println("String lives in " + String.class.getPackageName());
System.out.println("Math.max(3, 7) = " + Math.max(3, 7));
}
}
Output:
Date resolves to java.sql.Date
Other Date is java.util.Date
Same millis? true
java.sql.Date text 2024-03-19
java.sql has 8 characters
java.util has 9 characters
Imported packages 2
String lives in java.lang
Math.max(3, 7) = 7
TreeMap sorts its keys, so java.sql comes before java.util. Try deleting the import java.sql.Date; line and adding import java.sql.*;. The compiler then reports that Date is ambiguous on every line that uses it.
(Both Date classes are legacy types. New code uses java.time.LocalDate and friends, which are covered in the core APIs chapter. They're still the standard example of a name clash, both on the exam and in older code.)
Common questions
Does import java.util.*; make my program slower or bigger?
No. Imports exist only at compile time. The compiler writes fully qualified names into the class file, so wildcards and explicit imports produce identical bytecode.
Why can't I import a class from the default package? An import needs a package name, and the default package has none. Classes in the default package can only be used by other classes in the default package. That's one reason real code always declares a package.
Is import java.lang.*; an error?
No, it's redundant. It compiles and has no effect, because java.lang is always imported.
If two wildcards both provide Date, which one wins?
Neither. Using Date is ambiguous and doesn't compile. Add a single-type import for the one you want, or use fully qualified names.
Does import java.util.Map.*; compile?
Yes. It imports the types nested in Map, such as Entry. It doesn't import methods. For static methods and fields, use import static.
Should I use -cp, -classpath or --class-path?
They're identical, and all three work with both javac and java. Know all three for the exam, including which ones take one dash and which takes two.
Do I need to recompile after moving a class to another package? Yes. The package is part of the class's name, which is recorded in its own class file and in every class that uses it. The class file must also move to the matching directory.
Summary
- A package groups types and becomes the first part of their fully qualified names. Child packages are separate packages that only share a name prefix.
- An import lets you use simple names. A wildcard covers the types directly in one package, never child packages, fields or methods.
java.langand the current package are imported automatically. Importing them, or importing a class twice, is redundant but legal.- An explicit import beats a wildcard. Two wildcards with a shared name are ambiguous only where the name is used. Two explicit imports with the same simple name never compile.
- A fully qualified name always works and needs no import. Classes in the default package can't be imported.
javactakes file paths, and-dwrites class files into a directory tree that matches the packages.javatakes a fully qualified class name and finds it through-cp,-classpathor--class-path.- File order is package, imports, then types. Comments can go anywhere.
- Java 25 adds
import module, which ranks below single-type and on-demand imports.
Practice quiz
Test yourself with the packages, imports and class path quiz: 10 exam-style questions with explanations.
Previous: Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
Next: Creating Objects in Java: Constructors, Instance Initializers and Order of Initialization (OCP 21)
Related reading
- Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
- Java Generics Inheritance Rules and Wildcards: extends, super and ?
- Java Generics: Generic Classes and Generic Methods
- Java Package Access and the Class Path
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.