Package in Java: Basics Explained with Examples
A package in Java is a named group of related classes, interfaces, enums and records. Packages give every type a unique full name, map your code onto a clean folder structure, and decide which classes other code is allowed to use.
The JDK alone contains thousands of classes, and a typical application adds hundreds more. Without packages, two classes called Date or User could not exist side by side. This lesson explains how packages work in detail: the package statement, how package names map to folders, the default package, java.lang, fully qualified names, inspecting packages at runtime, naming rules and package-private access.
What Is a Package in Java?
A package is declared with a package statement on the first line of a source file. Every class in that file then belongs to the package.
package com.gocourse.greetings;
public class Welcome {
public static void main(String[] args) {
System.out.println("Hello from a package!");
System.out.println("Simple name: " + Welcome.class.getSimpleName());
System.out.println("Package: " + Welcome.class.getPackageName());
System.out.println("Full name: " + Welcome.class.getName());
}
}
Output:
Hello from a package!
Simple name: Welcome
Package: com.gocourse.greetings
Full name: com.gocourse.greetings.Welcome
How it works:
package com.gocourse.greetings;must be the first statement in the file. Only comments and blank lines may come before it.- A file can have at most one
packagestatement, so every class in the file shares the same package. - The class's fully qualified name is the package name, a dot and the simple name:
com.gocourse.greetings.Welcome. This is the name the JVM really uses.
| Part | Example | Meaning |
|---|---|---|
| Package name | com.gocourse.greetings | The group the class belongs to |
| Simple name | Welcome | The name written in the class declaration |
| Fully qualified name | com.gocourse.greetings.Welcome | Package plus simple name; unique worldwide |
How Java Package Names Map to Folders
Each dot-separated part of a package name is a folder. The source file should sit in a folder path that matches its package, and the compiled .class file is placed in the matching folder under the output directory.
project/
├── src/
│ └── com/
│ └── gocourse/
│ └── greetings/
│ └── Welcome.java (package com.gocourse.greetings;)
└── out/ (created by javac -d out)
└── com/
└── gocourse/
└── greetings/
└── Welcome.class
Compile and run from the project folder:
javac -d out src/com/gocourse/greetings/Welcome.java
java -cp out com.gocourse.greetings.Welcome
Output:
Hello from a package!
Simple name: Welcome
Package: com.gocourse.greetings
Full name: com.gocourse.greetings.Welcome
How it works:
javac -d outwrites the class file intoout/com/gocourse/greetings/, creating the folders from the package name.java -cp out com.gocourse.greetings.Welcometells the JVM to look inout(the classpath) and turn the dots into folders to findWelcome.class.- You run a packaged class by its fully qualified name, not by its file path.
Running it the wrong way gives a typical beginner error:
cd out/com/gocourse/greetings
java Welcome
Error: Could not find or load main class Welcome
Caused by: java.lang.NoClassDefFoundError: com/gocourse/greetings/Welcome (wrong name: Welcome)
The JVM found a file called Welcome.class, but the class inside it is really com.gocourse.greetings.Welcome. Always run from the classpath root with the full name.
The Default (Unnamed) Package
A file with no package statement belongs to the default package, also called the unnamed package. All the small single-file programs early in this tutorial used it.
// NoPackageDemo.java - no package statement
public class NoPackageDemo {
public static void main(String[] args) {
String packageName = NoPackageDemo.class.getPackageName();
System.out.println("Package name: '" + packageName + "'");
System.out.println("Is default package: " + packageName.isEmpty());
System.out.println("Full name: " + NoPackageDemo.class.getName());
}
}
Output:
Package name: ''
Is default package: true
Full name: NoPackageDemo
How it works:
- A class in the default package has an empty package name, so its full name is just its simple name.
- Classes in a named package cannot import classes from the default package. There is no name to import them by.
- The default package is fine for quick experiments, but every real project should put all of its classes in named packages.
java.lang: The Package You Never Import
Classes such as String, Math, Integer, System and Thread live in java.lang. The compiler imports java.lang into every file automatically, which is why you have never written an import for String.
package com.gocourse.greetings;
public class JavaLangDemo {
public static void main(String[] args) {
String course = "Java"; // java.lang.String
int longest = Math.max(4, 9); // java.lang.Math
Integer boxed = Integer.valueOf(42); // java.lang.Integer
System.out.println(course + " " + longest + " " + boxed);
System.out.println(String.class.getPackageName());
System.out.println(Math.class.getPackageName());
System.out.println(Thread.class.getPackageName());
}
}
Output:
Java 9 42
java.lang
java.lang
java.lang
How it works:
- Every class used here belongs to
java.lang, so noimportlines are needed. - Only
java.langitself is automatic. Its sub-packages, such asjava.lang.reflect, still need imports. - Classes in the same package as your class are also visible without an import.
Fully Qualified Names vs Imports
You can always refer to a class by its fully qualified name. An import statement simply lets you use the short name instead. Both styles compile to exactly the same bytecode.
package com.gocourse.greetings;
import java.time.LocalDate;
public class NamesDemo {
public static void main(String[] args) {
// Fully qualified names, no import needed
java.util.List<String> topics = new java.util.ArrayList<>();
topics.add("Packages");
topics.add("Imports");
// Simple name, thanks to the import above
LocalDate launch = LocalDate.of(2026, 1, 15);
System.out.println(topics + " launched on " + launch);
System.out.println("List type: " + topics.getClass().getName());
}
}
Output:
[Packages, Imports] launched on 2026-01-15
List type: java.util.ArrayList
How it works:
java.util.Listandjava.util.ArrayListare written in full, so no import is required for them.import java.time.LocalDate;lets the code writeLocalDateinstead ofjava.time.LocalDate.- Imports exist only at compile time. They do not load classes, copy code or make the program bigger.
Same Simple Name in Different Packages
Packages are what allow two classes to share a simple name. The JDK itself has both java.util.Date and java.sql.Date.
package com.gocourse.greetings;
import java.util.Date;
public class TwoDates {
public static void main(String[] args) {
Date utilDate = new Date(0); // java.util.Date (imported)
java.sql.Date sqlDate = java.sql.Date.valueOf("2026-01-15"); // written in full
System.out.println(utilDate.getClass().getName());
System.out.println(sqlDate.getClass().getName());
System.out.println("SQL date: " + sqlDate);
}
}
Output:
java.util.Date
java.sql.Date
SQL date: 2026-01-15
How it works:
- You cannot import two classes with the same simple name; the compiler would not know which
Dateyou mean. - The usual fix is to import the one you use most and write the other in full.
- The two classes are completely different types, even though their simple names match.
Inspecting Packages at Runtime
The Class object of any type can tell you its package. This is useful in logging, plugins and debugging tools.
package com.gocourse.greetings;
import java.util.Map;
public class InspectPackages {
public static void main(String[] args) {
Class<?>[] types = {
String.class,
java.util.ArrayList.class,
Map.Entry.class,
java.time.LocalDate.class,
InspectPackages.class
};
for (Class<?> type : types) {
System.out.printf("%-12s -> %s%n", type.getSimpleName(), type.getPackageName());
}
Package myPackage = InspectPackages.class.getPackage();
System.out.println("Package object name: " + myPackage.getName());
System.out.println("Nested class full name: " + Map.Entry.class.getName());
}
}
Output:
String -> java.lang
ArrayList -> java.util
Entry -> java.util
LocalDate -> java.time
InspectPackages -> com.gocourse.greetings
Package object name: com.gocourse.greetings
Nested class full name: java.util.Map$Entry
How it works:
getPackageName()returns the package as aString. It never returnsnull; for the default package it returns an empty string.getPackage()returns ajava.lang.Packageobject, which can also carry version information from a JAR manifest.- A nested type such as
Map.Entrybelongs to its outer class's package. Its binary name,java.util.Map$Entry, uses$to separate outer and inner class.
Packages Are Not Nested in Java
Package names look like a tree, but Java treats every package as completely separate. com.gocourse.shop and com.gocourse.shop.model have no special relationship. That has two practical effects.
First, a wildcard import does not include sub-packages:
package com.gocourse.greetings;
import java.util.*; // imports java.util classes only
public class WildcardDemo {
public static void main(String[] args) {
List<Integer> marks = new ArrayList<>(List.of(70, 85, 90));
Function<Integer, Integer> addBonus = mark -> mark + 5; // java.util.function.Function
System.out.println(addBonus.apply(marks.get(0)));
}
}
WildcardDemo.java:8: error: cannot find symbol
Function<Integer, Integer> addBonus = mark -> mark + 5; // java.util.function.Function
^
symbol: class Function
location: class WildcardDemo
1 error
How it works:
java.util.*brings inListandArrayList, butFunctionlives injava.util.function, a different package.- Adding
import java.util.function.Function;fixes the error, and the program then prints75.
Second, a "sub-package" gets no extra access to its "parent" package. Package-private members of com.gocourse.shop are just as hidden from com.gocourse.shop.model as from any other package.
Java Package Naming Rules and Conventions
A package name is a sequence of Java identifiers separated by dots. The rules come from the compiler; the conventions come from the community and make names unique.
| Package name | Valid? | Why |
|---|---|---|
com.gocourse.billing | Yes | Lowercase, reversed domain, clear meaning |
in.gocourse.lms.course | Yes | Reversed gocourse.in domain |
io.github.suriya.tools | Yes | Common form for personal GitHub projects |
com.gocourse.my-app | No | - is not allowed in identifiers; use my_app |
com.gocourse.2fa | No | A part cannot start with a digit; use _2fa |
com.gocourse.class | No | class is a keyword; use class_ or a different word |
java.mytools | Compiles, but cannot be used | The java prefix is reserved for the JDK |
Conventions to follow:
- Use only lowercase letters, so package names never clash with class names.
- Start with your organization's domain name reversed, then the project, then the area:
com.gocourse.shop.payment. - Keep each part short and meaningful. Prefer
paymentoverpaymentprocessingmodule.
Note: The JVM refuses to load a user class whose package starts with
java., throwing aSecurityException. Those names belong to the platform.
Package-Private Access Basics
A class, field, method or constructor declared without public, protected or private is package-private: visible to every class in the same package and hidden from all others. This is how a package keeps its helpers internal.
// src/com/gocourse/tools/TextTools.java
package com.gocourse.tools;
public class TextTools {
public static String title(String text) {
return Capitalizer.capitalizeWords(text); // same package: allowed
}
}
// Package-private class: no "public" keyword
class Capitalizer {
static String capitalizeWords(String text) {
StringBuilder result = new StringBuilder();
for (String word : text.split(" ")) {
result.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1))
.append(' ');
}
return result.toString().trim();
}
}
// src/com/gocourse/app/Main.java
package com.gocourse.app;
import com.gocourse.tools.TextTools;
public class Main {
public static void main(String[] args) {
System.out.println(TextTools.title("package basics in java"));
}
}
Output:
Package Basics In Java
How it works:
TextToolsispublic, soMainin another package can import and call it.Capitalizerhas no access modifier, so only classes incom.gocourse.toolscan see it.TextToolsuses it freely.- If
Maintriedimport com.gocourse.tools.Capitalizer;, compilation would fail witherror: Capitalizer is not public in com.gocourse.tools; cannot be accessed from outside package.
The full table of public, protected, package-private and private access is covered in the Java Packages overview lesson.
Real-World Example: A Class Origin Inspector
Tools such as loggers and error reporters often need to know where a class comes from: the JDK, a library or your own code. This program classifies classes by their package name.
package com.gocourse.inspector;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ClassOriginInspector {
static final String APP_PACKAGE_PREFIX = "com.gocourse.";
// Decides where a class comes from, using only its package name
static String origin(Class<?> type) {
String packageName = type.getPackageName();
if (packageName.isEmpty()) {
return "default package";
}
if (packageName.startsWith("java.") || packageName.startsWith("javax.") || packageName.startsWith("jdk.")) {
return "JDK";
}
if (packageName.startsWith(APP_PACKAGE_PREFIX)) {
return "our application";
}
return "third-party library";
}
// Groups classes by package, keeping the order they were first seen
static Map<String, List<String>> groupByPackage(List<Class<?>> types) {
Map<String, List<String>> groups = new LinkedHashMap<>();
for (Class<?> type : types) {
groups.computeIfAbsent(type.getPackageName(), key -> new ArrayList<>())
.add(type.getSimpleName());
}
return groups;
}
record Invoice(int number, double amount) { }
public static void main(String[] args) {
List<Class<?>> types = List.of(
String.class,
java.util.HashMap.class,
java.util.ArrayList.class,
java.time.Duration.class,
java.sql.Connection.class,
ClassOriginInspector.class,
Invoice.class
);
System.out.println("Class origins:");
for (Class<?> type : types) {
System.out.printf(" %-22s %s%n", type.getSimpleName(), origin(type));
}
System.out.println("Grouped by package:");
groupByPackage(types).forEach((packageName, names) ->
System.out.println(" " + packageName + " " + names));
}
}
Output:
Class origins:
String JDK
HashMap JDK
ArrayList JDK
Duration JDK
Connection JDK
ClassOriginInspector our application
Invoice our application
Grouped by package:
java.lang [String]
java.util [HashMap, ArrayList]
java.time [Duration]
java.sql [Connection]
com.gocourse.inspector [ClassOriginInspector, Invoice]
How it works:
- Package name as metadata.
origin()looks only atgetPackageName(). Names starting withjava.,javax.orjdk.are JDK classes, names undercom.gocourse.belong to the application, and anything else is treated as a library. - Nested types share the package. The
Invoicerecord is nested insideClassOriginInspector, so its package is alsocom.gocourse.inspector, and it is grouped with its outer class. - Grouping.
groupByPackage()uses aLinkedHashMapso packages appear in the order they were first seen.HashMapandArrayListend up together underjava.util. - Why it matters. Logging frameworks use this same idea to set different log levels for
com.gocourseand for library packages, and stack-trace tools use it to highlight your own code.
With the basics clear, the next lesson, Create Package in Java, walks through creating your own packages step by step: building the folder layout, compiling many files with javac -d, running them and packaging them into a JAR.