What is Package in Java - Types, Uses & Work
A package in Java is a namespace that groups related classes, interfaces, and sub-packages together. Packages help organize large codebases and prevent naming conflicts between classes.
Creating a Package
package com.uncodemy.app;
public class Student {
void display() {
System.out.println("Inside Student class");
}
}
Using a Package
import com.uncodemy.app.Student;
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.display();
}
}
Types of Packages
- Built-in Packages — provided by Java itself, such as
java.util,java.io, andjava.lang - User-defined Packages — packages created by developers to organize their own classes
How Packages Work
- The
packagestatement must be the first line in a Java source file - Packages map to a directory structure on disk, matching the package name
- Classes in the same package can access each other without an explicit import
- Classes from other packages need to be imported using the
importkeyword
Why Use Packages?
- Avoids naming conflicts between classes with the same name in different modules
- Makes large applications easier to navigate and maintain
- Controls access using access modifiers alongside package boundaries
The
java.lang package is imported automatically into every Java program, which is why classes like String and Math can be used without an explicit import.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.