Create Package in Java: Step-by-Step Guide with Examples
To create a package in Java, you choose a package name, put your source files in a matching folder structure, start each file with a package statement, and compile with javac -d so the class files land in the right folders. After that you run the program by its fully qualified class name.
Every real Java project is built this way, whether you use a plain terminal, an IDE, Maven or Gradle. In this lesson you will create a package from scratch, add more classes and sub-packages, import between them, fix the most common "package does not exist" errors, compile a whole project at once, document a package with package-info.java, and ship the result as a runnable JAR.
Steps to Create a Package in Java
| Step | What you do | Example |
|---|---|---|
| 1 | Choose a package name | com.gocourse.hello |
| 2 | Create matching folders | src/com/gocourse/hello/ |
| 3 | Add a package statement to each file | package com.gocourse.hello; |
| 4 | Compile with javac -d | javac -d out src/com/gocourse/hello/Main.java |
| 5 | Run with the fully qualified name | java -cp out com.gocourse.hello.Main |
The sections below walk through each step with commands you can run in a terminal. If you need a refresher on what a package is, see Package in Java.
Step 1: Choose a Package Name
Start with your organization's internet domain reversed, then add the project name and, later, an area of the project. Use only lowercase letters.
Domain: gocourse.com
Reversed: com.gocourse
Project package: com.gocourse.hello
Later sub-areas: com.gocourse.hello.model, com.gocourse.hello.util
How it works:
- The reversed domain makes your names practically unique, because no one else owns your domain.
- Lowercase names never clash with class names, which start with a capital letter.
- If you have no domain,
io.github.<username>is a common choice for personal projects.
Step 2: Create the Folder Structure
Each part of the package name becomes one folder inside a source root, usually called src.
mkdir -p hello-app/src/com/gocourse/hello
cd hello-app
On Windows Command Prompt, the same folders are created with:
mkdir hello-app\src\com\gocourse\hello
cd hello-app
The project now looks like this:
hello-app/
└── src/
└── com/
└── gocourse/
└── hello/
How it works:
mkdir -pcreates every missing folder in the path at once.srcis the source root. It is not part of the package name; only the folders below it are.
Step 3: Add the package Statement
Create src/com/gocourse/hello/Main.java. The package statement must be the first statement in the file.
package com.gocourse.hello;
public class Main {
public static void main(String[] args) {
System.out.println("Hello from package " + Main.class.getPackageName());
}
}
How it works:
package com.gocourse.hello;placesMainin that package, so its full name becomescom.gocourse.hello.Main.- The folder path
com/gocourse/hellomatches the package name. Build tools and IDEs rely on this match to find your source files. - Only comments and blank lines may appear above the
packagestatement. Imports go below it.
Step 4: Compile the Package with javac -d
Run javac from the project folder (hello-app). The -d option sets the output folder.
javac -d out src/com/gocourse/hello/Main.java
find out -name "*.class"
Output:
out/com/gocourse/hello/Main.class
How it works:
-d outtells the compiler to create folders underoutthat match each class's package, then write the class file there.- Without
-d,javacwritesMain.classnext toMain.java, mixing sources and compiled files. - Keeping compiled output in its own folder (
out,bin, or Maven'starget/classes) makes it easy to clean and package later.
Step 5: Run the Class by Its Fully Qualified Name
java -cp out com.gocourse.hello.Main
Output:
Hello from package com.gocourse.hello
How it works:
-cp outputs theoutfolder on the classpath, the list of places where the JVM looks for classes.- The JVM turns
com.gocourse.hello.Maininto the pathcom/gocourse/hello/Main.classand finds it underout.
Running with only the simple name fails, because there is no class called just Main:
java -cp out Main
Error: Could not find or load main class Main
Caused by: java.lang.ClassNotFoundException: Main
Adding More Classes to the Same Package
Any number of classes can share a package. Classes in the same package can use each other without imports, and they can use package-private members (members with no access modifier).
Create src/com/gocourse/hello/Greeter.java:
package com.gocourse.hello;
public class Greeter {
public String greet(String name, int hour) {
return GreetingWords.forHour(hour) + ", " + name + "!";
}
}
// Package-private helper: visible only inside com.gocourse.hello
class GreetingWords {
static String forHour(int hour) {
if (hour < 12) {
return "Good morning";
} else if (hour < 17) {
return "Good afternoon";
}
return "Good evening";
}
}
Then update Main.java to use it:
package com.gocourse.hello;
public class Main {
public static void main(String[] args) {
Greeter greeter = new Greeter(); // same package: no import needed
System.out.println(greeter.greet("Asha", 9));
System.out.println(greeter.greet("Ravi", 14));
System.out.println(greeter.greet("Meena", 20));
}
}
Compile both files and run:
javac -d out src/com/gocourse/hello/*.java
java -cp out com.gocourse.hello.Main
Output:
Good morning, Asha!
Good afternoon, Ravi!
Good evening, Meena!
How it works:
MainusesGreeterwith noimport, because both are incom.gocourse.hello.GreetingWordshas nopublickeyword.Greetercan call it, but code in any other package cannot even see it. This keeps helpers private to the package.- A file may hold several top-level classes, but only one can be
public, and that one must match the file name. Most projects still put each class in its own file.
Creating Sub-Packages and Importing Between Them
Larger programs split code into sub-packages by responsibility. Here model holds data types and util holds calculations.
src/com/gocourse/hello/
├── Main.java
├── Greeter.java
├── model/
│ └── Student.java
└── util/
└── MarksCalculator.java
src/com/gocourse/hello/model/Student.java:
package com.gocourse.hello.model;
public record Student(String name, int[] marks) { }
src/com/gocourse/hello/util/MarksCalculator.java:
package com.gocourse.hello.util;
import com.gocourse.hello.model.Student;
public final class MarksCalculator {
private MarksCalculator() { }
public static double average(Student student) {
int total = 0;
for (int mark : student.marks()) {
total += mark;
}
return (double) total / student.marks().length;
}
}
src/com/gocourse/hello/Main.java:
package com.gocourse.hello;
import com.gocourse.hello.model.Student;
import com.gocourse.hello.util.MarksCalculator;
public class Main {
public static void main(String[] args) {
Student asha = new Student("Asha", new int[]{88, 92, 79});
Student ravi = new Student("Ravi", new int[]{70, 65, 81});
System.out.printf("%s: %.1f%n", asha.name(), MarksCalculator.average(asha));
System.out.printf("%s: %.1f%n", ravi.name(), MarksCalculator.average(ravi));
}
}
Compile every file under src and run:
javac -d out $(find src -name "*.java")
java -cp out com.gocourse.hello.Main
Output:
Asha: 86.3
Ravi: 72.0
How it works:
StudentandMarksCalculatorare in different packages fromMain, soMainimports both. They must also bepublicto be used across packages.MarksCalculatorimportsStudenttoo, becauseutilandmodelare separate packages.com.gocourse.hello.modelis not "inside"com.gocourse.helloin any special way. Java treats each package independently; the folder nesting is only for organization.- Asha's average is
(88 + 92 + 79) / 3 = 86.33..., printed as86.3; Ravi's is216 / 3 = 72.0.
Fixing "package does not exist" Errors
The most frequent error after creating packages is the compiler saying a package does not exist. Suppose Student.java is missing its package statement:
// src/com/gocourse/hello/model/Student.java (package line forgotten)
public record Student(String name, int[] marks) { }
javac -d out $(find src -name "*.java")
Output (the first of several similar errors; MarksCalculator.java reports the same problem):
src/com/gocourse/hello/Main.java:3: error: package com.gocourse.hello.model does not exist
import com.gocourse.hello.model.Student;
^
How it works:
- Without a
packagestatement,Studentbelongs to the default package, no matter which folder it sits in. The packagecom.gocourse.hello.modelthen has no classes, so every import of it fails, and every use ofStudentadds acannot find symbolerror. - The fix is to add
package com.gocourse.hello.model;as the first line ofStudent.java. One missing line can cause many errors, so always fix the first error first and compile again.
| Error | Usual cause | Fix |
|---|---|---|
package ... does not exist | Missing or misspelled package line, or the file was not compiled | Check the first line of the file and compile all sources |
cannot find symbol (class) | Class not imported, or the import names the wrong package | Add the correct import |
X is not public in ...; cannot be accessed from outside package | Using a package-private class from another package | Make it public or move the caller into the same package |
Could not find or load main class | Running without the full name or with the wrong -cp | Run java -cp out package.name.ClassName from the project root |
Compiling Every File in a Project
Listing files by hand does not scale. These commands compile an entire source tree.
# Linux and macOS: pass every .java file under src
javac -d out $(find src -name "*.java")
# Any platform: give the source root and the main class; javac finds the rest
javac -d out --source-path src src/com/gocourse/hello/Main.java
On Windows Command Prompt, build a list of files first and pass it with @:
dir /s /b src\*.java > sources.txt
javac -d out @sources.txt
Then run as usual:
java -cp out com.gocourse.hello.Main
Output:
Asha: 86.3
Ravi: 72.0
How it works:
$(find src -name "*.java")expands to every source file, so nothing is forgotten.- With
--source-path src,javacstarts fromMain.javaand compiles every class it references, looking them up in folders that match their packages. This is why the folder structure must mirror the package names. @sources.txttellsjavacto read its file list from a text file, which avoids command-line length limits on large projects.
Note: From JDK 22 you can also run a multi-file program straight from source with
java src/com/gocourse/hello/Main.java. The launcher works out the source root from the package name and compiles the other classes it needs in memory. This is handy for small programs; real projects still compile to class files or use a build tool.
Documenting a Package with package-info.java
A file named package-info.java holds the documentation (and annotations) for a whole package. It contains only a Javadoc comment and the package statement.
Create src/com/gocourse/hello/model/package-info.java:
/**
* Data types for the hello app.
* <p>
* Every type in this package is a record that holds a student's
* details. Calculations live in {@code com.gocourse.hello.util}.
*/
package com.gocourse.hello.model;
Generate HTML documentation for all packages:
javadoc -d docs --source-path src -subpackages com.gocourse.hello
How it works:
package-info.javais the only place to write package-level Javadoc. Its comment appears on the package's summary page in the generated docs.-subpackages com.gocourse.hellodocuments that package and every package below it. Opendocs/index.htmlin a browser to see the result.- The file compiles to
package-info.class, which also stores any package-level annotations.
Packaging Your Classes into a JAR File
A JAR (Java ARchive) bundles the compiled package folders into one file that is easy to share and run.
jar --create --file hello.jar --main-class com.gocourse.hello.Main -C out .
java -jar hello.jar
Output:
Asha: 86.3
Ravi: 72.0
How it works:
-C out .changes intooutand adds everything inside, so the JAR keeps thecom/gocourse/hello/...folder structure. The JVM needs that structure to find classes by package.--main-classwrites the entry point into the JAR's manifest, sojava -jar hello.jarknows which class to start.jar --list --file hello.jarshows the entries, includingcom/gocourse/hello/Main.classandcom/gocourse/hello/model/Student.class.
Real-World Example: A Multi-Package Library App
This project uses three packages, each with one job: model for data, service for logic (with a package-private helper), and app for the entry point.
library-app/src/com/gocourse/library/
├── app/
│ └── LibraryApp.java
├── model/
│ └── Book.java
└── service/
├── Catalog.java
└── SearchIndex.java (package-private)
model/Book.java:
package com.gocourse.library.model;
public record Book(String isbn, String title, String author, int year) {
public Book {
if (isbn == null || isbn.isBlank()) {
throw new IllegalArgumentException("ISBN is required");
}
}
}
service/SearchIndex.java:
package com.gocourse.library.service;
import com.gocourse.library.model.Book;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// No "public": an internal detail of the service package
class SearchIndex {
private final Map<String, List<Book>> booksByAuthor = new HashMap<>();
void add(Book book) {
booksByAuthor.computeIfAbsent(normalize(book.author()), key -> new ArrayList<>()).add(book);
}
List<Book> byAuthor(String author) {
return booksByAuthor.getOrDefault(normalize(author), List.of());
}
private static String normalize(String text) {
return text.trim().toLowerCase();
}
}
service/Catalog.java:
package com.gocourse.library.service;
import com.gocourse.library.model.Book;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Catalog {
private final List<Book> books = new ArrayList<>();
private final SearchIndex index = new SearchIndex(); // same package: no import
public void add(Book book) {
books.add(book);
index.add(book);
}
public List<String> titlesBy(String author) {
return index.byAuthor(author).stream().map(Book::title).toList();
}
public List<Book> oldestFirst() {
return books.stream().sorted(Comparator.comparingInt(Book::year)).toList();
}
public int size() {
return books.size();
}
}
app/LibraryApp.java:
package com.gocourse.library.app;
import com.gocourse.library.model.Book;
import com.gocourse.library.service.Catalog;
public class LibraryApp {
public static void main(String[] args) {
Catalog catalog = new Catalog();
catalog.add(new Book("978-0001", "Learning Java", "Asha Kumar", 2021));
catalog.add(new Book("978-0002", "Database Design", "Ravi Shankar", 2019));
catalog.add(new Book("978-0003", "Clean Java Code", "Asha Kumar", 2024));
catalog.add(new Book("978-0004", "Networks Made Simple", "Meena Raj", 2017));
System.out.println("Books in catalog: " + catalog.size());
System.out.println("By Asha Kumar: " + catalog.titlesBy(" asha KUMAR "));
System.out.println("Oldest first:");
for (Book book : catalog.oldestFirst()) {
System.out.println(" " + book.year() + " " + book.title());
}
System.out.println("Started from package: " + LibraryApp.class.getPackageName());
}
}
Compile, run and package it from the library-app folder:
javac -d out $(find src -name "*.java")
java -cp out com.gocourse.library.app.LibraryApp
jar --create --file library.jar --main-class com.gocourse.library.app.LibraryApp -C out .
java -jar library.jar
Output (printed once by each java command):
Books in catalog: 4
By Asha Kumar: [Learning Java, Clean Java Code]
Oldest first:
2017 Networks Made Simple
2019 Database Design
2021 Learning Java
2024 Clean Java Code
Started from package: com.gocourse.library.app
How it works:
- One job per package.
modelknows nothing about searching,serviceknows nothing about how the program starts, andapponly wires things together. Each folder is easy to find and to change. - Public API, private details.
Catalogispublic, soLibraryAppcan use it.SearchIndexis package-private, so only classes inservicecan touch it. IfLibraryApptriedimport com.gocourse.library.service.SearchIndex;, the compiler would stop witherror: SearchIndex is not public in com.gocourse.library.service; cannot be accessed from outside package. - Imports cross package borders.
CatalogandSearchIndeximportBookfrommodel, andLibraryAppimports from bothmodelandservice. - Search ignores spacing and case.
SearchIndextrims and lowercases author names, so" asha KUMAR "finds both of Asha Kumar's books. - Same result from classes or JAR. The JAR keeps the package folders, so
java -jar library.jarruns exactly likejava -cp out ....
In Maven and Gradle projects the source root is src/main/java instead of src, but every package rule in this lesson stays the same. For how packages control visibility and imports in general, revisit the Java Packages overview.