☕ Java
Built-in Packages
Java ships with a rich standard library organised into packages under the java and javax namespaces. These built-in packages provide data structures, I/O, networking, concurrency, database access, XML processing, GUI components, and much more. Knowing which package contains which functionality, and understanding the most important classes in the most frequently used packages, is foundational knowledge for every Java developer.
java.lang — The Foundation Package
java.lang is the only package that is automatically imported into every Java source file — you never need to write import java.lang.*. It contains the classes that are so fundamental to the Java language that they are treated as built-in. Every Java program implicitly depends on java.lang regardless of what it does.
Object is the root of the entire class hierarchy and provides the fundamental methods: equals(), hashCode(), toString(), getClass(), clone(), wait(), notify(), and notifyAll(). Every Java class implicitly extends Object. String is the most-used class in Java programs — immutable, final, and supported by special syntax (string literals and the + operator). System provides access to standard I/O (System.in, System.out, System.err), system properties, the current time, and the GC. Math provides static mathematical functions. The wrapper classes (Integer, Double, Long, Boolean, Character, etc.) box primitives into objects and provide parsing, conversion, and constant utilities.
Thread and Runnable are in java.lang because threading is considered fundamental to the Java platform. Enum is the base class for all enum types. AutoCloseable is the interface for try-with-resources. Iterable is the interface for for-each loop support. Comparable is the interface for natural ordering. The exception classes (Throwable, Exception, RuntimeException, Error) and common runtime exceptions (NullPointerException, IllegalArgumentException, ArrayIndexOutOfBoundsException) are all in java.lang.
StringBuilder and StringBuffer (for mutable string building) are in java.lang. Runtime gives access to the JVM runtime — available memory, processors, and garbage collection. Process and ProcessBuilder allow launching and controlling external OS processes.
Java
// ── java.lang is automatically imported — no import statement needed: ──
// Object — root of hierarchy:
Object obj = new Object();
String str = obj.toString(); // from Object
int h = obj.hashCode(); // from Object
Class c = obj.getClass(); // from Object
// String — immutable, special syntax:
String name = "Alice"; // string literal creates String object
String greeting = "Hello, " + name;// + operator for String
String upper = name.toUpperCase();
boolean starts = name.startsWith("Al");
// Wrapper classes — boxing and parsing:
int i = Integer.parseInt("42");
double d = Double.parseDouble("3.14");
String s = Integer.toString(255, 16); // "ff" — radix 16
Integer bi = Integer.MAX_VALUE; // 2147483647
boolean bo = Boolean.valueOf("true");
// Math — static mathematical functions:
double sq = Math.sqrt(16.0); // 4.0
double pi = Math.PI; // 3.14159...
int abs = Math.abs(-42); // 42
double pow = Math.pow(2, 10); // 1024.0
int max = Math.max(10, 20); // 20
double rnd = Math.random(); // 0.0 to 1.0
// System — I/O and environment:
System.out.println("Standard output");
System.err.println("Error output");
long now = System.currentTimeMillis(); // epoch milliseconds
long nano = System.nanoTime(); // high-res timer
String path = System.getProperty("user.home");
int procs = Runtime.getRuntime().availableProcessors();
// StringBuilder:
String built = new StringBuilder()
.append("Hello").append(", ").append("World").toString();
// Thread:
Thread.sleep(100); // sleep current thread
System.out.println(Thread.currentThread().getName());java.util — The Collections and Utilities Package
java.util is the second most important package after java.lang. It contains the Collections Framework — the interfaces and implementations for lists, sets, maps, queues, and deques that form the backbone of almost every Java program. It also contains utility classes for dates, random numbers, scanning input, sorting, and more.
The Collections Framework is centred on three root interfaces: Collection (for all collections), Map (for key-value mappings), and Iterator (for traversal). The most-used implementations are ArrayList (dynamic array list), LinkedList (doubly linked list), HashMap (hash-based map), LinkedHashMap (insertion-ordered map), TreeMap (sorted map), HashSet (hash-based set), LinkedHashSet (insertion-ordered set), and TreeSet (sorted set). ArrayDeque serves as both a stack and a queue.
Collections provides static utility methods: sort(), binarySearch(), reverse(), shuffle(), min(), max(), frequency(), and unmodifiableXxx() wrappers. Arrays provides similar utilities for arrays: sort(), binarySearch(), fill(), copyOf(), and toString(). Objects provides null-safe utility methods: requireNonNull(), equals(), hash(), and toString().
Java 8 added the Stream API (java.util.stream) for declarative data processing, Optional for null-safe value containers, and functional interfaces (java.util.function) including Function, Predicate, Consumer, Supplier, and BiFunction. Java 9-17 added immutable collection factories: List.of(), Set.of(), Map.of(), and Map.entry().
Java
import java.util.*;
import java.util.stream.*;
// ── Collections Framework — most used implementations: ─────────────────
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
Set<String> hashSet = new HashSet<>();
Set<String> treeSet = new TreeSet<>(); // sorted
Map<String, Integer> hashMap = new HashMap<>();
Map<String, Integer> linkedMap = new LinkedHashMap<>(); // insertion order
Map<String, Integer> treeMap = new TreeMap<>(); // sorted by key
Queue<String> queue = new ArrayDeque<>();
Deque<String> deque = new ArrayDeque<>();
// ── Immutable factory methods (Java 9+): ──────────────────────────────
List<String> names = List.of("Alice", "Bob", "Charlie");
Set<Integer> numbers = Set.of(1, 2, 3, 4, 5);
Map<String, Integer> ages = Map.of("Alice", 30, "Bob", 25);
// ── Collections utility methods: ──────────────────────────────────────
List<Integer> nums = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6));
Collections.sort(nums); // [1, 1, 2, 3, 4, 5, 6, 9]
Collections.reverse(nums); // [9, 6, 5, 4, 3, 2, 1, 1]
Collections.shuffle(nums); // random order
int max = Collections.max(nums);
List<Integer> immutable = Collections.unmodifiableList(nums);
// ── Arrays utility: ────────────────────────────────────────────────────
int[] arr = {5, 3, 8, 1, 9};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // [1, 3, 5, 8, 9]
int idx = Arrays.binarySearch(arr, 5); // 2
// ── Optional — null-safe container: ───────────────────────────────────
Optional<String> opt = Optional.ofNullable(null);
String value = opt.orElse("default"); // "default"
opt.ifPresent(System.out::println); // prints nothing
// ── Stream API — declarative processing: ──────────────────────────────
List<String> filtered = names.stream()
.filter(n -> n.startsWith("A"))
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
Map<Integer, List<String>> byLength = names.stream()
.collect(Collectors.groupingBy(String::length));
// ── Other utilities: ──────────────────────────────────────────────────
Random rnd = new Random();
int dice = rnd.nextInt(6) + 1; // 1-6
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();Key Standard Library Packages Overview
Beyond java.lang and java.util, several other packages are essential for different domains of programming. Knowing which package handles which concern prevents wasted time searching for classes in the wrong place.
java.io provides the classic stream-based I/O system: InputStream, OutputStream, Reader, Writer, FileInputStream, FileOutputStream, FileReader, FileWriter, BufferedReader, BufferedWriter, PrintWriter, and PrintStream. java.nio (New I/O, Java 4) provides channel-based I/O: FileChannel, ByteBuffer, and the Selector model for non-blocking I/O. java.nio.file (Java 7) provides the modern file system API: Path, Paths, Files, StandardOpenOption, FileVisitor, and WatchService.
java.net provides networking: URL, HttpURLConnection, Socket, ServerSocket, InetAddress, and DatagramSocket. java.net.http (Java 11) provides the modern HTTP client: HttpClient, HttpRequest, and HttpResponse.
java.util.concurrent provides high-level concurrency utilities: ExecutorService, ThreadPoolExecutor, Future, CompletableFuture, locks (ReentrantLock, ReadWriteLock), atomic variables (AtomicInteger, AtomicReference), and concurrent collections (ConcurrentHashMap, BlockingQueue, CopyOnWriteArrayList).
java.sql provides JDBC for database access: Connection, Statement, PreparedStatement, ResultSet, DriverManager, and DataSource. java.time (Java 8) provides the modern date-time API: LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant, Duration, Period, and DateTimeFormatter.
java.lang.reflect provides reflection: Class, Method, Field, Constructor, and Modifier. java.util.logging provides the standard logging API. java.util.regex provides Pattern and Matcher for regular expressions.
Java
// ── java.io — classic file and stream I/O: ───────────────────────────
import java.io.*;
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) System.out.println(line);
} catch (IOException e) { e.printStackTrace(); }
// ── java.nio.file — modern file system (Java 7+): ────────────────────
import java.nio.file.*;
Path path = Path.of("data", "users.csv");
String text = Files.readString(path); // read all text
List<String> lines = Files.readAllLines(path); // all lines
Files.writeString(path, "content", StandardOpenOption.CREATE);
Files.copy(path, Path.of("backup.csv"));
boolean exists = Files.exists(path);
// ── java.net.http — modern HTTP client (Java 11+): ───────────────────
import java.net.http.*;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users"))
.GET().build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode()); // 200
System.out.println(response.body());
// ── java.util.concurrent — thread pools and futures: ─────────────────
import java.util.concurrent.*;
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> future = pool.submit(() -> computeExpensiveValue());
Integer result = future.get(); // blocks until complete
pool.shutdown();
CompletableFuture.supplyAsync(() -> fetchData())
.thenApply(data -> processData(data))
.thenAccept(System.out::println);
// ── java.time — modern date/time (Java 8+): ──────────────────────────
import java.time.*;
LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDate birth = LocalDate.of(1990, 5, 15);
long age = ChronoUnit.YEARS.between(birth, today);
Instant epoch = Instant.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formatted = today.format(fmt);
// ── java.util.regex — pattern matching: ──────────────────────────────
import java.util.regex.*;
Pattern p = Pattern.compile("\d{4}-\d{2}-\d{2}");
Matcher m = p.matcher("Date: 2025-05-30");
if (m.find()) System.out.println("Found: " + m.group());Related Topics in Packages and Access Control
Package Concept
A package in Java is a namespace that groups related classes, interfaces, enums, and annotations into a logical unit. Packages solve three fundamental problems in large software systems: name collision (two classes can have the same simple name if they are in different packages), access control (package-private visibility limits access to the same package), and organisation (related types live together and can be found intuitively). Every Java class belongs to a package — either explicitly declared or the unnamed default package.
User-defined Packages
User-defined packages are packages you create to organise your own application's classes and interfaces. They follow the same rules as Java's built-in packages — the package declaration must be the first statement in the file, the directory structure must match the package hierarchy, and access modifiers control visibility across package boundaries. Designing a meaningful package structure is a foundational software engineering skill that directly affects how maintainable and navigable a codebase remains as it grows.
import
The import statement allows you to use a class, interface, or enum by its simple name rather than its fully qualified name. Without an import, every reference to java.util.ArrayList requires writing the full name java.util.ArrayList. With import java.util.ArrayList, you write simply ArrayList. Imports are a compile-time convenience — they have no effect on performance, do not load classes, and are not present in the compiled bytecode. The compiler uses them only to resolve simple names to fully qualified names.
Static Import
Static import allows you to access static members — static fields and static methods — of a class by their simple name without qualifying them with the class name. Introduced in Java 5, static import reduces verbosity when a few specific static members are used repeatedly. It is most useful for mathematical constants and functions, assertion methods in tests, and constants. Like regular imports, static imports are a compile-time convenience with no runtime effect.