Package in Java: Basics Explained with Examples

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 224 of 306

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 package statement, 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.
PartExampleMeaning
Package namecom.gocourse.greetingsThe group the class belongs to
Simple nameWelcomeThe name written in the class declaration
Fully qualified namecom.gocourse.greetings.WelcomePackage 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 out writes the class file into out/com/gocourse/greetings/, creating the folders from the package name.
  • java -cp out com.gocourse.greetings.Welcome tells the JVM to look in out (the classpath) and turn the dots into folders to find Welcome.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 no import lines are needed.
  • Only java.lang itself is automatic. Its sub-packages, such as java.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.List and java.util.ArrayList are written in full, so no import is required for them.
  • import java.time.LocalDate; lets the code write LocalDate instead of java.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 Date you 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 a String. It never returns null; for the default package it returns an empty string.
  • getPackage() returns a java.lang.Package object, which can also carry version information from a JAR manifest.
  • A nested type such as Map.Entry belongs 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 in List and ArrayList, but Function lives in java.util.function, a different package.
  • Adding import java.util.function.Function; fixes the error, and the program then prints 75.

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 nameValid?Why
com.gocourse.billingYesLowercase, reversed domain, clear meaning
in.gocourse.lms.courseYesReversed gocourse.in domain
io.github.suriya.toolsYesCommon form for personal GitHub projects
com.gocourse.my-appNo- is not allowed in identifiers; use my_app
com.gocourse.2faNoA part cannot start with a digit; use _2fa
com.gocourse.classNoclass is a keyword; use class_ or a different word
java.mytoolsCompiles, but cannot be usedThe 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 payment over paymentprocessingmodule.

Note: The JVM refuses to load a user class whose package starts with java., throwing a SecurityException. 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:

  • TextTools is public, so Main in another package can import and call it.
  • Capitalizer has no access modifier, so only classes in com.gocourse.tools can see it. TextTools uses it freely.
  • If Main tried import com.gocourse.tools.Capitalizer;, compilation would fail with error: 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:

  1. Package name as metadata. origin() looks only at getPackageName(). Names starting with java., javax. or jdk. are JDK classes, names under com.gocourse. belong to the application, and anything else is treated as a library.
  2. Nested types share the package. The Invoice record is nested inside ClassOriginInspector, so its package is also com.gocourse.inspector, and it is grouped with its outer class.
  3. Grouping. groupByPackage() uses a LinkedHashMap so packages appear in the order they were first seen. HashMap and ArrayList end up together under java.util.
  4. Why it matters. Logging frameworks use this same idea to set different log levels for com.gocourse and 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.

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 Package in Java: Basics Explained with Examples and get answers drawn from it.

Signed-in readers only.