Create Package in Java: Step-by-Step Guide with Examples

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 225 of 306

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

StepWhat you doExample
1Choose a package namecom.gocourse.hello
2Create matching folderssrc/com/gocourse/hello/
3Add a package statement to each filepackage com.gocourse.hello;
4Compile with javac -djavac -d out src/com/gocourse/hello/Main.java
5Run with the fully qualified namejava -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 -p creates every missing folder in the path at once.
  • src is 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; places Main in that package, so its full name becomes com.gocourse.hello.Main.
  • The folder path com/gocourse/hello matches 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 package statement. 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 out tells the compiler to create folders under out that match each class's package, then write the class file there.
  • Without -d, javac writes Main.class next to Main.java, mixing sources and compiled files.
  • Keeping compiled output in its own folder (out, bin, or Maven's target/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 out puts the out folder on the classpath, the list of places where the JVM looks for classes.
  • The JVM turns com.gocourse.hello.Main into the path com/gocourse/hello/Main.class and finds it under out.

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:

  • Main uses Greeter with no import, because both are in com.gocourse.hello.
  • GreetingWords has no public keyword. Greeter can 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:

  • Student and MarksCalculator are in different packages from Main, so Main imports both. They must also be public to be used across packages.
  • MarksCalculator imports Student too, because util and model are separate packages.
  • com.gocourse.hello.model is not "inside" com.gocourse.hello in 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 as 86.3; Ravi's is 216 / 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 package statement, Student belongs to the default package, no matter which folder it sits in. The package com.gocourse.hello.model then has no classes, so every import of it fails, and every use of Student adds a cannot find symbol error.
  • The fix is to add package com.gocourse.hello.model; as the first line of Student.java. One missing line can cause many errors, so always fix the first error first and compile again.
ErrorUsual causeFix
package ... does not existMissing or misspelled package line, or the file was not compiledCheck the first line of the file and compile all sources
cannot find symbol (class)Class not imported, or the import names the wrong packageAdd the correct import
X is not public in ...; cannot be accessed from outside packageUsing a package-private class from another packageMake it public or move the caller into the same package
Could not find or load main classRunning without the full name or with the wrong -cpRun 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, javac starts from Main.java and 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.txt tells javac to 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.java is the only place to write package-level Javadoc. Its comment appears on the package's summary page in the generated docs.
  • -subpackages com.gocourse.hello documents that package and every package below it. Open docs/index.html in 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 into out and adds everything inside, so the JAR keeps the com/gocourse/hello/... folder structure. The JVM needs that structure to find classes by package.
  • --main-class writes the entry point into the JAR's manifest, so java -jar hello.jar knows which class to start.
  • jar --list --file hello.jar shows the entries, including com/gocourse/hello/Main.class and com/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:

  1. One job per package. model knows nothing about searching, service knows nothing about how the program starts, and app only wires things together. Each folder is easy to find and to change.
  2. Public API, private details. Catalog is public, so LibraryApp can use it. SearchIndex is package-private, so only classes in service can touch it. If LibraryApp tried import com.gocourse.library.service.SearchIndex;, the compiler would stop with error: SearchIndex is not public in com.gocourse.library.service; cannot be accessed from outside package.
  3. Imports cross package borders. Catalog and SearchIndex import Book from model, and LibraryApp imports from both model and service.
  4. Search ignores spacing and case. SearchIndex trims and lowercases author names, so " asha KUMAR " finds both of Asha Kumar's books.
  5. Same result from classes or JAR. The JAR keeps the package folders, so java -jar library.jar runs exactly like java -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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Create Package in Java: Step-by-Step Guide with Examples and get answers drawn from it.

Signed-in readers only.