Back to Study Material Java

Packages in Java

A package in Java is a namespace that groups related classes and interfaces together. Packages serve two purposes: they organize large codebases into logic...

Packages in Java

Organizing Code with Java Packages

A package in Java is a namespace that groups related classes and interfaces together. Packages serve two purposes: they organize large codebases into logical folders, and they prevent naming conflicts. Two classes in different packages can have the same name without clashing, because the package name is part of each class's fully qualified name. For example, java.util.Date and java.sql.Date are two completely separate classes.

Declaring and Importing Packages Every source file that belongs to a package begins with a package statement as its very first line: package com.company.project.service. This must match the directory structure on disk. To use a class from another package, you either write its fully qualified name each time (java.util.ArrayList) or add an import statement at the top of the file: import java.util.ArrayList. A wildcard import (import java.util.*) imports all public types in the package but does not import sub-packages.

Built-in Java Packages The Java standard library is itself organized into packages. java.lang is special—it is imported automatically into every class and contains String, Math, Object, System, and all primitive wrapper classes. java.util contains the collections framework (List, Map, Set), Scanner, Date, and Random. java.io and java.nio handle file and stream operations. java.net covers networking. Knowing which package a commonly used class belongs to is a practical skill for everyday coding.

Access Control Interaction Package membership interacts with access modifiers. The default (package-private) access level—when you write no modifier at all—allows a class member to be used by any class in the same package but not from outside it. This is more restrictive than protected (which also allows subclasses) and more permissive than private. Understanding this interaction helps you design APIs that expose the right things to the right callers.

Code Example: // File: com/store/Product.java package com.store;

public class Product { private String name; double price; // package-private

public Product(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } }

Interview Tip: Expect an interview question about whether import makes the code run faster by pre-loading classes. It does not. Import is purely a compile-time convenience that lets you use short names. The class loading itself happens at runtime only when the class is first used. Clarifying this shows you understand the difference between compilation and class loading.