Java Packages: Package Names, Imports and Static Imports
How Java packages organize classes and prevent name clashes: reverse-domain package names, fully qualified names, single-type and on-demand imports, resolving conflicts like java.util.Date vs java.sql.Date, static imports, module imports in Java 25, and placing classes into packages and directories.
kvi5hnuCode Sprout team member11 min readOn this page
So far every class in this course has lived in one flat space. Real programs contain hundreds or thousands of classes and use libraries written by other people. Java groups classes into packages: named collections that keep your work organized and separate it from the code libraries you use.
This article covers naming packages, using classes from other packages (imports and static imports), and putting your own classes into a package. The next article covers package access and the class path, which tells the JVM where to find classes.
Package Names
The main reason for packages is to guarantee unique class names. Suppose two programmers both write an Employee class. As long as the classes live in different packages, there's no conflict.
To make a package name globally unique, the convention is to start with an Internet domain name written in reverse, since domain names are unique. Then add subpackages for projects:
| Domain | Package prefix | Project package | Fully qualified class name |
|---|---|---|---|
example.com | com.example | com.example.payroll | com.example.payroll.Employee |
apache.org | org.apache | org.apache.commons.lang3 | org.apache.commons.lang3.StringUtils |
google.com | com.google | com.google.common.collect | com.google.common.collect.ImmutableList |
The full name com.example.payroll.Employee, package plus class, is the class's fully qualified name.
Naming conventions you should follow:
- Package names are all lowercase:
com.example.payroll, nevercom.example.Payroll. - If a domain part isn't a legal identifier, adapt it: a hyphen becomes an underscore (
my-site.org→org.my_site), and a leading digit gets an underscore (123go.com→com._123go). - Never put your own code in packages starting with
java.orjavax.. Those belong to the JDK.
Using Classes from Other Packages
A class can use all classes from its own package and all public classes from other packages.
There are two ways to access a public class in another package. The first is to write its fully qualified name every time:
java.time.LocalDate today = java.time.LocalDate.now();
That works, but it's tedious. The usual way is an import declaration, which gives you a shorthand. After an import, you no longer have to spell out the full name.
Single-type and on-demand imports
import declarations go at the top of the source file, after the package declaration (if any) and before the class. You can import a specific class (a single-type import):
import java.time.LocalDate;
or all public classes of a package (an on-demand, or wildcard, import):
import java.time.*;
Either way, you can now write
LocalDate today = LocalDate.now();
without the package prefix.
import java.time.LocalDate; | import java.time.*; | |
|---|---|---|
| Imports | exactly one class | all public classes of java.time that you use |
| Readability | the reader sees exactly what you use | less typing |
| Effect on class file size or speed | none | none: imports are a compile-time convenience only |
| Risk | none | can create name conflicts when two wildcard packages share a class name |
The * form imports one package only. There's no way to import a whole hierarchy: import java.*; is an error (package java does not exist, because no classes live directly in java), and import java.*.*; isn't even valid syntax (';' expected).
You never need to import java.lang. String, Math, System, Integer and friends are always available.
Resolving name conflicts
Most of the time you just import what you need and don't think about it. You must pay attention only when two packages contain classes with the same name. The classic case is Date, which exists in both java.util and java.sql:
import java.util.*;
import java.sql.*;
public class A {
Date d; // error: reference to Date is ambiguous
}
The compiler can't tell which Date you mean. Fix it with a single-type import, which takes precedence over wildcard imports:
import java.util.*;
import java.sql.*;
import java.util.Date; // Date now means java.util.Date
If you really need both classes, use the fully qualified name for (at least) one of them:
var startTime = new java.util.Date();
var today = new java.sql.Date(System.currentTimeMillis());
Other common clashes are java.util.List and java.awt.List, and your own Element, Node or Path classes versus library ones.
Imports are only a compiler convenience
Locating classes in packages is the compiler's job. Class files always use full package names to refer to other classes; the bytecode contains no imports. So an import:
- doesn't load or link any code,
- doesn't make your program bigger or slower, and
- can always be replaced by writing fully qualified names.
Static Imports
A variant of import imports static methods and fields rather than classes. Then you can use them without the class name prefix:
import static java.lang.Math.*;
double r = sqrt(pow(x, 2) + pow(y, 2)); // instead of Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))
You can also import one specific member:
import static java.lang.Math.sqrt;
import static java.lang.System.out;
out.println(sqrt(2)); // System.out.println(Math.sqrt(2))
Static imports make the most sense where the class name adds nothing:
-
Mathematical formulas:
sqrt(pow(x, 2) + pow(y, 2))reads much better than theMath.-qualified version. -
Enum constants:
javaimport java.time.DayOfWeek; import static java.time.DayOfWeek.*; DayOfWeek w = FRIDAY; // same as DayOfWeek.FRIDAY -
Test assertions and fluent APIs:
import static org.junit.jupiter.api.Assertions.*;gives youassertEquals(...), andimport static java.util.stream.Collectors.*;gives youtoList(),groupingBy(...).
On the other hand, out.println(...) or a bare exit(0) are less clear than System.out.println(...) and System.exit(0). Readers wonder where out and exit come from.
import static java.lang.Math.*;
import static java.time.DayOfWeek.FRIDAY;
import java.time.DayOfWeek;
public class Solution {
public static void main(String[] args) {
double x = 3, y = 4;
System.out.println(sqrt(pow(x, 2) + pow(y, 2))); // Math.sqrt, Math.pow
System.out.println(PI > 3); // Math.PI
DayOfWeek day = FRIDAY;
System.out.println(day.plus(1));
}
}
5.0
true
SATURDAY
Module Import Declarations (Java 25)
Java 25 finalized module import declarations (JEP 511). A single line imports all public top-level classes and interfaces of all packages exported by a module:
import module java.base; // java.util.*, java.io.*, java.time.*, java.util.stream.*, ...
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Linus"); // java.util
Path p = Path.of("notes.txt"); // java.nio.file
LocalDate d = LocalDate.of(2026, 11, 13); // java.time
System.out.println(names + " " + p + " " + d);
}
}
This is mostly a convenience for scripts, small programs and teaching. Compact source files (Java 25, the simplified void main() programs) implicitly import java.base. Ambiguities are resolved as before: a single-type import such as import java.util.Date; wins over module and wildcard imports. Modules are covered in detail in the last part of this course.
Putting a Class into a Package
To place a class in a package, write a package declaration as the first statement of the source file (only comments may precede it):
package com.example.payroll;
import java.time.LocalDate; // imports come after the package declaration
public class Employee {
. . .
}
If a source file has no package declaration, its classes belong to the unnamed package (also called the default package), which has no name. All example classes in this course so far live there. That's fine for small experiments, but real code always uses named packages. Classes in the unnamed package can't be imported from a named package.
Directories must match packages
Place source files in a subdirectory that matches the full package name. All files in com.example.payroll belong in the directory com/example/payroll (com\example\payroll on Windows). The compiler puts class files into the same structure.
Here's a program spread over two packages:

com/example/payroll/Employee.java:
package com.example.payroll;
import java.time.LocalDate;
public class Employee {
private final String name;
private double salary;
private final LocalDate startDate;
public Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
startDate = LocalDate.of(year, month, day);
}
public String getName() { return name; }
public double getSalary() { return salary; }
public LocalDate getStartDate() { return startDate; }
public void giveRaise(double pct) {
salary += salary * pct / 100;
}
}
com/mycompany/PayrollApp.java:
package com.mycompany;
import com.example.payroll.Employee; // the class lives in another package
import static java.lang.System.out;
public class PayrollApp {
public static void main(String[] args) {
var omar = new Employee("Omar Haddad", 52000, 2019, 9, 2);
omar.giveRaise(4);
out.println("name=" + omar.getName() + ",salary=" + omar.getSalary());
}
}
Compile and run from the base directory, the one that contains com:
javac com/mycompany/PayrollApp.java
java com.mycompany.PayrollApp
name=Omar Haddad,salary=54080.0
The compiler finds and compiles com/example/payroll/Employee.java automatically, because PayrollApp uses it. Note the asymmetry:
javacworks with files: path separators (/or\) and the.javaextension.javaloads a class: dot separators and no extension.
In real projects, IDEs and build tools (Maven, Gradle) keep sources and class files in separate trees: sources under src/main/java/com/example/..., compiled classes under target/classes or build/classes/java/main. The package-to-directory rule applies to both trees.
Common questions
Do wildcard imports make compilation slower or programs bigger? No. Imports affect only how the compiler resolves names. The class files contain fully qualified names either way. Teams ban wildcard imports for readability and to avoid sudden name clashes when a library adds a class, not for performance.
Should I use import module java.base; in normal code?
It is mostly meant for scripts, teaching and quick prototypes. In larger code bases, explicit single-type imports make dependencies obvious and avoid ambiguity, for example java.util.List versus java.awt.List with import module java.desktop.
Why can't I import a class from the default package? Since Java 1.4, the language doesn't allow it. Code in a named package has no way to refer to classes in the unnamed package. Put every class that is meant to be reused into a named package.
Does the folder structure really have to match the package?
For the JVM's class lookup, yes. com.example.App must be found at com/example/App.class relative to a class path entry. javac doesn't enforce it for sources, but every build tool and IDE expects sources in the matching directories too.
What's a good package structure for an application?
Group by feature (com.example.shop.order, com.example.shop.payment) rather than by technical layer (controllers, services, daos). Feature packages keep related classes together and let you use package access to hide implementation classes.
Summary
- Packages group classes and guarantee unique names. Use your reversed domain name as a prefix, all lowercase:
com.example.project. - Subpackages are unrelated to their parent packages as far as the compiler is concerned.
- You can use all classes of your own package and all public classes of other packages, by fully qualified name or via
import. import pkg.Class;imports one class;import pkg.*;imports a package on demand. Imports have no runtime cost.java.langis always imported.- Resolve ambiguities (
java.util.Datevsjava.sql.Date) with a single-type import or fully qualified names. import staticimports static members. Use it for math, enum constants and test assertions, and sparingly elsewhere.- Java 25's
import module java.base;imports every exported package of a module. package com.example.x;must be the first statement. The file must live incom/example/x/. Compile with file paths and run with class names.
Practice Questions
Your company owns the domain acme-tools.io. What's a good package name for its billing project?
io.acme_tools.billing: reverse the domain, replace the hyphen with an underscore (hyphens aren't legal in identifiers), use lowercase, and add the project name.
Does import java.util.*; let you use java.util.jar.JarFile without another import?
No. java.util.jar is a separate, unrelated package. A wildcard import covers one package only. You need import java.util.jar.JarFile; (or import java.util.jar.*;).
A file imports java.util.* and java.awt.* and declares List<String> names. What happens, and how do you fix it?
Compile error: reference to List is ambiguous, because both packages contain a List type. Add the single-type import import java.util.List;, which takes precedence over both wildcard imports.
Does import java.time.*; make the class file bigger or the program slower than importing just LocalDate?
No. Imports exist only at compile time. The class file refers to classes by fully qualified name either way. The only difference is readability (and the possibility of name conflicts).
A file com/shop/Cart.java starts with package com.shop;. From which directory do you run javac and java, and with which arguments?
From the base directory containing com: javac com/shop/Cart.java (a file path), then java com.shop.Cart (a class name, assuming Cart has a main method).
When is a static import a good idea, and when not?
Good: math-heavy code (sqrt, PI), enum constants (FRIDAY), test assertions (assertEquals), stream collectors. Not good: when the bare name hides its origin (out, exit, of), or when wildcard static imports from several classes could clash.
Previous: Java Records: Compact Data Classes with Canonical and Compact Constructors
Related reading
- Modular JARs and Reflective Access in Java: opens and open modules
- Java Module requires and exports: Dependencies and Exported Packages
- Your First Java Program Explained: Classes, main, Statements and Comments
- Java Records: Compact Data Classes with Canonical and Compact Constructors
- Java Object Construction: Overloading, Default Fields, this(), and Initialization Blocks

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.