Java Packages
What is a Package?
A package is a namespace that organizes related classes and interfaces. It prevents naming conflicts and controls access. Packages map directly to directory structures on the filesystem.
Built-in Java Packages
| Package | Contains |
|---|---|
java.lang | Core classes: String, Math, Object, System, Thread (auto-imported) |
java.util | Collections, Scanner, Date, Random, Arrays |
java.io | File I/O: File, InputStream, OutputStream, BufferedReader |
java.net | Networking: URL, Socket, HttpURLConnection |
java.math | BigInteger, BigDecimal |
java.time | Modern date/time API: LocalDate, LocalDateTime, Duration |
// File: com/example/utils/MathUtils.java
package com.example.utils; // package declaration — must be first line
public class MathUtils {
public static int square(int n) { return n * n; }
public static double circleArea(double r) { return Math.PI * r * r; }
}
package com.example;
// Import a specific class
import com.example.utils.MathUtils;
// Import all classes in a package (wildcard)
import java.util.*;
// Static import — import static members directly
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
public class Main {
public static void main(String[] args) {
// Using imported class
System.out.println(MathUtils.square(5)); // 25
System.out.println(MathUtils.circleArea(3.0)); // 28.27...
// Using java.util classes
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println(names); // [Alice, Bob]
// Using static import — no Math. prefix needed
System.out.println(PI); // 3.141592653589793
System.out.println(sqrt(16.0)); // 4.0
}
}
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.