Java Tutorial

Packages & Imports

Organizing code with package, import, and fully qualified names

What are Java Packages?

In a large project, different libraries might use the same name for a class (e.g., User or Config). To prevent this name collision, Java provides Packages. They act like "folders" or "namespaces" for your code.
The most famous package is java.util, which contains everything from the Java Collections Framework.
java
package com.mygame.physics; // Must be the FIRST line!

public class Gravity {
    // This class lives inside the 'physics' package!
}

Importing Other Classes

To use a class from another package, you must "bring it in" using the import keyword.
java
import java.util.ArrayList; // Just one class!
import java.util.List;

// Or search for all classes in a package!
import java.util.*; // Use sparingly!

Automatic Imports

Wait! You never have to import the most common classes like String, System, or Math. They live in the java.lang package, which is automatically imported into every Java file.
java
String name = "Alpha"; // No import needed!

Static Imports (JAVA 5+)

A Static Import allows you to use static members (methods or constants) of a class without mentioning the class name itself.
java
import static java.lang.Math.*;

double res = sqrt(16) + PI; // Instead of Math.sqrt and Math.PI!

Summary

TermDescription
PackageA folder for organizing your code
ImportBringing external classes into your file
java.utilStandard package for collections
java.langThe ONLY automatic package (no import!)
FQNjava.util.ArrayList (Total path to a class)
Best ForCode separation, preventing name collisions
CollisionOccurs when same name used in same scope
SafePackages make your code much easier to maintain
ModularGroup related code into separate folders
FQN Saveu1.set(10); (Fully Qualified Names!)
NamingConvention: Reverse domain name (com.google.util)
HeaderThe package line MUST be the first line!
StructureJava folder structure MUST match the package name!
PrivatePackages can have "Package-Private" access (default)
ExportControlling what other people can see in your package
RefactorMove whole packages to separate "Modules" (Java 9+)
HierarchySub-packages like com.google.util.math
StandardEstablished and trusted worldwide for 25+ years
JVMThe JVM uses package names to find .class files!
AliasJava DOES NOT allow name aliases for imports!
AmbiguityUse FQN if two imported packages have the SAME class name!
ProjectA "Project" is a collection of related packages
LibraryA "Library" is a pre-written collection of packages
StaticImport methods/constants with import static
Wildcard* imports ONLY classes, not entire sub-packages!