← Back to Chapters

Java Packages

? Java Packages

? Quick Overview

In Java, a package is a namespace that groups related classes and interfaces together. Packages help organize large projects, avoid naming conflicts, and improve code reusability and maintenance.

? Key Concepts

  • Packages act like folders for Java classes
  • They provide access control (public, protected, default)
  • Java provides built-in packages and allows user-defined packages
  • Classes are accessed using the package name

? Syntax / Theory

A package is declared using the package keyword at the very top of a Java source file.

? View Code Example
// Declaring a package named com.example.util
package com.example.util;

public class Helper {
    public void greet() {
        System.out.println("Hello from Helper class");
    }
}
? Interactive: Package Structure Visualizer

Change the names below to see how Java Packages map to Folders.

. .
?src
└──?com
    └──?google
        └──?maps
            └──?App.java
// Inside App.java
package com.google.maps;
 
public class App { ... }

? Code Example(s)

? View Code Example
// Using a class from another package
import com.example.util.Helper;

public class MainApp {
    public static void main(String[] args) {
        Helper h = new Helper();
        h.greet();
    }
}

? Live Output / Explanation

Output

Hello from Helper class

The Helper class is accessed using its package name. The import statement allows us to use the class without writing the full package path every time.

? Tips & Best Practices

  • Always use meaningful and reverse-domain package names
  • Place the package statement as the first line in the file
  • Use packages to separate layers like model, service, and controller
  • Avoid using the default package in real projects

? Try It Yourself

  • Create your own package and add two related classes
  • Access one class from another package using import
  • Experiment with removing the import and using the full package name