Java Fundamentals
Open in the Padhaiko app1.1 Overview of Java ecosystem (JDK, JVM, JRE)
Java achieves platform independence through its "Write Once, Run Anywhere" (WORA) execution model. Instead of compiling directly to machine-specific instructions, the Java compiler (javac) translates .java source files into platform-neutral bytecode (.class files). At runtime, a platform-specific Java Virtual Machine (JVM) loads, verifies, and executes that bytecode on the host operating system and hardware.
Source (.java) ──[ javac ]──> Bytecode (.class) ──[ JVM ]──> Native Machine Code
├── ClassLoader Subsystem
├── Runtime Data Areas
└── Execution Engine (Interpreter + JIT + GC)JDK, JRE, and JVM
JVM, JRE, and JDK
- JVM (Java Virtual Machine): An abstract computing engine that provides the runtime environment for executing Java bytecode. It handles class loading, bytecode verification, memory management (garbage collection), and Just-In-Time (JIT) compilation. The JVM is platform-dependent (Windows, Linux, macOS each have their own JVM implementation), which enables bytecode to remain platform-independent.
- JRE (Java Runtime Environment): The software package required to run compiled Java applications. Formally,
JRE = JVM + Core Class Libraries(such asjava.lang,java.util,java.io, and supporting configuration files). - JDK (Java Development Kit): The complete software kit required to develop, compile, debug, and run Java applications. Formally,
JDK = JRE + Development Tools(javaccompiler,jararchiver,javadocgenerator,jdbdebugger,jshell, and profiling utilities).
| Component | Primary Role | Contains | Platform Dependency | Typical User |
|---|---|---|---|---|
| JVM | Executes .class bytecode | ClassLoader, Runtime Memory Areas, Interpreter, JIT, GC | Platform-dependent | Runtime engine (internal) |
| JRE | Runs existing Java programs | JVM + Standard API libraries (rt.jar / modular JRT image) | Platform-dependent | End users running Java apps |
| JDK | Develops and runs Java programs | JRE + javac, jar, javadoc, jdb, jshell | Platform-dependent | Java software developers |
Internal Architecture of the JVM
- ClassLoader Subsystem: Performs three sequential phases for
.classfiles:- Loading: Bootstrap, Platform (Extension), and Application class loaders locate and load bytecode into memory.
- Linking: Verification (checks bytecode structural safety), Preparation (allocates static fields with default values), and Resolution (replaces symbolic references with direct references).
- Initialization: Assigns static variables their declared values and executes
static { ... }blocks.
- Runtime Data Areas:
- Method Area (Metaspace in Java 8+): Stores class metadata, runtime constant pool, and static method bytecode (shared across threads).
- Heap: Stores all object instances and arrays; managed by the Garbage Collector (shared across threads).
- JVM Stacks: One stack per thread; each method call pushes a stack frame holding local variables, operand stack, and frame data.
- PC Register & Native Method Stack: Per-thread pointers to the current bytecode instruction and support for native (C/C++) JNI calls.
- Execution Engine: Combines a bytecode Interpreter (fast startup, executes instructions line by line) with a JIT (Just-In-Time) Compiler (detects hot loops/methods and compiles them to native machine code for high throughput) and a Garbage Collector (GC) (reclaims unreachable heap objects).
1.2 Evolution of Java
Originally created by James Gosling's team at Sun Microsystems (started as Oak in 1991, publicly released as Java 1.0 in 1995) and later stewarded by Oracle, Java transitioned to a predictable six-month release cadence starting with Java 9/10, with Long-Term Support (LTS) releases every few years (Java 8, 11, 17, 21).
| Release | Year | Type | Key Language & Platform Features |
|---|---|---|---|
| Java 1.0 / 1.1 | 1995–1997 | Legacy | Core OOP, Applets, AWT, JDBC, JavaBeans, inner classes |
| Java 5 (1.5) | 2004 | Major | Generics, enhanced for-each loop, autoboxing, enum, varargs, annotations |
| Java 8 | 2014 | LTS | Lambda expressions, Streams API, Optional, java.time, default/static interface methods |
| Java 11 | 2018 | LTS | Standard java.net.http.HttpClient, var in lambda parameters, single-file java Foo.java launch |
| Java 17 | 2021 | LTS | Records, sealed classes, switch expressions, text blocks ("""), pattern matching for instanceof |
| Java 21 | 2023 | LTS | Virtual threads (Project Loom), pattern matching for switch, record patterns, sequenced collections |
1.3 Modern development tools (Maven, Gradle, IntelliJ, VS Code)
Professional Java projects rely on build automation tools to compile code, download third-party libraries from Maven Central, run tests, and package deployable JAR/WAR artifacts, paired with Integrated Development Environments (IDEs).
Build Tools: Apache Maven vs. Gradle
| Aspect | Apache Maven | Gradle |
|---|---|---|
| Configuration File | Declarative XML (pom.xml) | Groovy (build.gradle) or Kotlin (build.gradle.kts) DSL |
| Core Philosophy | Strict convention over configuration + fixed lifecycle phases | Flexible Directed Acyclic Graph (DAG) of tasks |
| Build Performance | Re-runs phases unless configured otherwise | Incremental builds, build cache, persistent daemon |
| Coordinates | groupId, artifactId, version (GAV) | Same Maven Central GAV coordinates (implementation("...")) |
| Wrapper Script | mvnw / mvnw.cmd (optional) | gradlew / gradlew.bat (standard, pins Gradle version) |
- Standard Maven Directory Layout:
src/main/java(application source),src/main/resources(config/properties),src/test/java(unit tests),target/(compiled output). - Maven Default Lifecycle Phases (in order):
validate->compile->test->package->verify->install->deploy. Runningmvn packageautomatically runs all preceding phases.
Modern IDEs: IntelliJ IDEA and VS Code
- IntelliJ IDEA (Community / Ultimate): The industry-standard Java IDE offering deep static analysis, automated refactoring (extract method, safe rename), visual debugger with expression evaluation, built-in Maven/Gradle tool windows, and native Spring Boot support (Ultimate).
- Visual Studio Code (VS Code): A lightweight, extensible editor powered for Java by the Extension Pack for Java (Eclipse JDT Language Server, Debugger for Java, Test Runner, Maven/Gradle integration) and Spring Boot Extension Pack. Ideal on resource-constrained laptops.
1.4 Review of core Java OOP, collections and exception handling
Core Object-Oriented Programming (OOP)
The Four Pillars of OOP in Java
- Encapsulation: Bundling data (fields) and behavior (methods) inside a class while hiding internal state with
privatefields and exposing controlledpublicgetters/setters or domain methods. - Inheritance (
extends): Allowing a subclass to reuse and extend fields and methods of a single superclass (class SavingsAccount extends Account). Java supports single class inheritance and multiple interface implementation (implements). - Polymorphism: Taking many forms:
- Compile-time (Static) Polymorphism: Method overloading (same method name, different parameter list within a class).
- Runtime (Dynamic) Polymorphism: Method overriding (subclass redefines superclass method with
@Override; the JVM dispatches based on the actual runtime object type).
- Abstraction: Hiding implementation details and exposing essential contracts via
abstractclasses (partial implementation, can hold instance state) andinterfaces (pure behavior contracts, plusdefaultandstaticmethods since Java 8).
Java Collections Framework (JCF)
The java.util package defines reusable generic data structures rooted at Collection<E> (List, Set, Queue) and the separate Map<K, V> hierarchy.
| Interface | Implementation | Ordering | Duplicates | Null Keys/Elements | Typical Time Complexity |
|---|---|---|---|---|---|
List<E> | ArrayList | Insertion order (indexed) | Allowed | Allowed | get(i) O(1), add amortized O(1) |
List<E> | LinkedList | Insertion order | Allowed | Allowed | get(i) O(n), head/tail add/remove O(1) |
Set<E> | HashSet | Unordered | No | 1 null | add/contains/remove O(1) average |
Set<E> | LinkedHashSet | Insertion order | No | 1 null | O(1) average |
Set<E> | TreeSet | Sorted (Comparable/Comparator) | No | No null | O(log n) (Red-Black tree) |
Map<K,V> | HashMap | Unordered | Unique keys | 1 null key | get/put O(1) average |
Map<K,V> | TreeMap | Sorted by key | Unique keys | No null key | O(log n) |
Queue<E> | ArrayDeque | FIFO / Deque | Allowed | No null | O(1) amortized at both ends |
- Generics (
<T>): Provide compile-time type safety (e.g.,List<String>prevents accidentally inserting anIntegerand eliminates manual casts). equals()andhashCode()Contract: Whenever two objects are equal underequals(), they must return the samehashCode()integer—otherwiseHashSetandHashMapfail to locate keys reliably.
Exception Handling
All exceptions inherit from java.lang.Throwable, which splits into Error (serious JVM failures like OutOfMemoryError, not normally caught) and Exception:
- Checked Exceptions (subclasses of
ExceptionexcludingRuntimeException, e.g.,IOException,SQLException): Checked at compile time; methods must either handle them withtry-catchor declarethrows. - Unchecked Exceptions (subclasses of
RuntimeException, e.g.,NullPointerException,IllegalArgumentException,IndexOutOfBoundsException): Represent programming logic errors; not required inthrowsdeclarations.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ConfigLoader {
public static String readFirstLine(String path) throws IOException {
// try-with-resources automatically closes BufferedReader even if an exception occurs
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line = reader.readLine();
if (line == null) {
throw new IllegalStateException("Configuration file is empty: " + path);
}
return line;
}
}
}1.5 Functional programming: Lambda, expressions and streams API
Introduced in Java 8, functional programming features treat behavior as data, enabling concise, declarative collection processing.
Functional Interfaces and Lambda Expressions
A functional interface has exactly one abstract method (optionally marked @FunctionalInterface). A lambda expression provides an inline implementation of that single abstract method: (parameters) -> expression or (parameters) -> { statements; }.
| Interface | Abstract Method Signature | Purpose | Example Lambda |
|---|---|---|---|
Predicate<T> | boolean test(T t) | Boolean condition / filter | s -> s.length() > 3 |
Function<T, R> | R apply(T t) | Transform T into R | String::toUpperCase (method ref) |
Consumer<T> | void accept(T t) | Side-effect action, no return | System.out::println |
Supplier<T> | T get() | Lazy value factory, no input | ArrayList::new |
The Streams API
A Stream<T> is a lazy, non-mutating pipeline over a data source (such as a List or array). It does not store elements and runs only when a terminal operation is invoked:
- Source:
list.stream(),Arrays.stream(arr),Stream.of(...). - Intermediate Operations (lazy, return a new
Stream):filter(Predicate),map(Function),flatMap(...),sorted(...),distinct(),limit(n). - Terminal Operations (trigger execution, produce result or side effect):
collect(Collectors.toList())/.toList()(Java 16+),reduce(identity, accumulator),count(),sum()(onIntStream),findFirst()(returnsOptional<T>),forEach(Consumer).
import java.util.List;
public class StreamDemo {
public static void main(String[] args) {
List<Integer> scores = List.of(45, 78, 92, 60, 85);
int passedTotal = scores.stream()
.filter(s -> s >= 60) // keeps 78, 92, 60, 85
.mapToInt(Integer::intValue) // unbox to IntStream
.sum(); // 315
List<String> labels = scores.stream()
.filter(s -> s >= 80) // keeps 92, 85
.sorted() // 85, 92
.map(s -> "Score:" + s)
.toList();
System.out.println("Total = " + passedTotal + ", Top = " + labels);
}
}1.6 Introduction to modern features like records and sealed classes
Java 17 and Java 21 modernized data modeling by replacing verbose boilerplate POJOs and unconstrained class hierarchies with records and sealed classes.
Records (Standard in Java 16+)
A record declares an immutable data carrier in one line. The compiler automatically generates:
private finalfields for each component,- a canonical constructor,
- accessor methods named after each component (e.g.,
student.gpa(), notgetGpa()), equals(),hashCode(), andtoString().
public record Student(int rollNo, String name, double gpa) {
// Compact constructor for validation without repeating field assignments
public Student {
if (gpa < 0.0 || gpa > 4.0) {
throw new IllegalArgumentException("GPA must be between 0.0 and 4.0");
}
}
}Records cannot extend other classes (they implicitly extend java.lang.Record) and are implicitly final, though they can implement interfaces and declare static or instance methods.
Sealed Classes and Interfaces (Standard in Java 17+)
A sealed class or interface restricts which classes or interfaces may extend or implement it via the permits clause. Every permitted subtype must declare exactly one modifier:
final: cannot be extended further,sealed: restricts its own subtypes withpermits,non-sealed: re-opens the hierarchy for arbitrary extension.
public sealed interface Shape permits Circle, Rectangle {
double area();
}
public record Circle(double radius) implements Shape {
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public record Rectangle(double width, double height) implements Shape {
@Override
public double area() {
return width * height;
}
}When paired with pattern matching for switch (Java 21), the compiler verifies exhaustiveness across all permitted subtypes of a sealed type without needing a default branch:
static String describe(Shape shape) {
return switch (shape) {
case Circle c -> "Circle of radius " + c.radius();
case Rectangle r -> "Rectangle " + r.width() + "x" + r.height();
};
}Worked Examples
1.1
Consider a Java record Order(String category, int qty, double unitPrice) {} and the following list of orders:
Order("Book", 2, 450.0)Order("Pen", 10, 25.0)Order("Book", 1, 600.0)Order("Notebook", 4, 150.0)
Trace a Java Streams API pipeline that keeps only orders whose line total (qty * unitPrice) is at least 500.0, applies a 10% discount to each kept line total, and computes the grand total payable.
Write the Java stream pipeline using filter, mapToDouble, and sum:
record Order(String category, int qty, double unitPrice) {}
List<Order> orders = List.of(
new Order("Book", 2, 450.0),
new Order("Pen", 10, 25.0),
new Order("Book", 1, 600.0),
new Order("Notebook", 4, 150.0)
);
double grandTotal = orders.stream()
.mapToDouble(o -> o.qty() * o.unitPrice())
.filter(total -> total >= 500.0)
.map(discounted -> discounted * 0.90)
.sum();Trace each element through the pipeline stages:
Order("Book", 2, 450.0): line total =2 * 450.0 = 900.0(>= 500.0, kept) -> after 10% discount =900.0 * 0.90 = 810.0.Order("Pen", 10, 25.0): line total =10 * 25.0 = 250.0(< 500.0, filtered out).Order("Book", 1, 600.0): line total =1 * 600.0 = 600.0(>= 500.0, kept) -> after 10% discount =600.0 * 0.90 = 540.0.Order("Notebook", 4, 150.0): line total =4 * 150.0 = 600.0(>= 500.0, kept) -> after 10% discount =600.0 * 0.90 = 540.0.
Sum the remaining discounted values at the terminal .sum() operation: grandTotal = 810.0 + 540.0 + 540.0 = 1890.0.
The filtered orders are "Book" (900.0), "Book" (600.0), and "Notebook" (600.0). After a 10% discount (810.0 + 540.0 + 540.0), the grand total returned by .sum() is 1890.0.
1.2
Model a payment domain using a sealed interface Payment permitting two records: CashPayment(double amount) and CardPayment(double amount, double feeRate). Write a Java 21 pattern-matching switch method netAmount(Payment p) that subtracts the fee (amount * feeRate) for card payments, and compute the sum of netAmount for CashPayment(1200.0) and CardPayment(2000.0, 0.025).
Define the sealed hierarchy and pattern-matching switch (no default case is needed because the sealed interface permits only CashPayment and CardPayment):
public sealed interface Payment permits CashPayment, CardPayment {}
public record CashPayment(double amount) implements Payment {}
public record CardPayment(double amount, double feeRate) implements Payment {}
static double netAmount(Payment p) {
return switch (p) {
case CashPayment c -> c.amount();
case CardPayment card -> card.amount() * (1.0 - card.feeRate());
};
}Evaluate each instance:
- For
CashPayment(1200.0):netAmount = 1200.0. - For
CardPayment(2000.0, 0.025): fee =2000.0 * 0.025 = 50.0, sonetAmount = 2000.0 - 50.0 = 1950.0. - Combined sum =
1200.0 + 1950.0 = 3150.0.
CashPayment(1200.0) yields 1200.0 and CardPayment(2000.0, 0.025) yields 1950.0, giving a combined net amount of 3150.0.
1.3
How should a student answer the past exam question: "Explain the relationship between JDK, JRE, and JVM, and explain how the JIT compiler improves JVM performance"?
Structure the Hierarchy First: Draw the nested containment diagram (JDK = JRE + Dev Tools, JRE = JVM + Libraries) and define each component in 1–2 crisp sentences, emphasizing that the JVM is platform-dependent while .class bytecode is platform-independent (WORA).
Explain the Execution Engine and JIT:
- State that the JVM initially interprets bytecode instructions sequentially for fast startup.
- Explain that interpreting every loop iteration repeatedly is slow, so the JIT (Just-In-Time) compiler profiles execution to detect frequently executed code ("hotspots" / hot methods) and compiles them into native machine code cached in memory for subsequent calls.
A complete exam answer defines JVM (bytecode execution engine), JRE (JVM + standard libraries to run apps), and JDK (JRE + javac, jdb, jar to develop apps), includes the nested containment diagram, and explains that JIT compilation optimizes hotspot methods by translating bytecode into native CPU instructions at runtime.
Exercises
Practice Exercises — Java Fundamentals
Distinguish between JDK, JRE, and JVM. Explain why Java bytecode is called platform-independent even though the JVM itself is platform-dependent.
Definitions and Relationship:
- JVM (Java Virtual Machine): Executes
.classbytecode, manages heap/stack memory, performs garbage collection, and runs the interpreter and JIT compiler. - JRE (Java Runtime Environment): Combines the JVM with Java's standard runtime class libraries (
java.lang,java.util, etc.) needed to run programs. - JDK (Java Development Kit): Superset of JRE that adds development tools (
javac,jar,javadoc,jdb).
Why Bytecode is Platform-Independent: javac compiles .java files into a single standardized .class bytecode format specified by the JVM specification, independent of CPU architecture or OS. Each OS vendor/provider builds a platform-specific JVM that translates that identical bytecode into local machine instructions, achieving "Write Once, Run Anywhere".
JDK = JRE + Development Tools and JRE = JVM + Core Class Libraries. Bytecode is platform-independent because javac emits one standardized instruction set across all systems, while each operating system uses its own platform-dependent JVM to execute that bytecode natively.
Compare Apache Maven and Gradle as modern Java build tools, and list the core phases of Maven's default build lifecycle in execution order.
Maven vs. Gradle Comparison:
- Configuration Format: Maven uses declarative XML (
pom.xml); Gradle uses Groovy (build.gradle) or Kotlin (build.gradle.kts) scripts. - Execution Model: Maven follows a fixed linear lifecycle with convention-over-configuration; Gradle models tasks as a flexible Directed Acyclic Graph (DAG).
- Performance: Gradle supports incremental builds, a persistent build daemon, and build caching out of the box, generally giving faster builds on large multi-module projects.
Maven Default Lifecycle Phases (Sequential Order): validate -> compile -> test -> package -> verify -> install -> deploy.
Maven configures builds declaratively in pom.xml around a fixed lifecycle (validate, compile, test, package, verify, install, deploy), whereas Gradle uses Groovy/Kotlin build scripts (build.gradle / build.gradle.kts), task DAGs, and incremental caching for faster customizable builds.
Differentiate between Checked and Unchecked exceptions in Java with examples. Show how try-with-resources prevents resource leaks compared to a classic try-finally block.
Checked vs. Unchecked Exceptions:
- Checked Exceptions (
Exceptionsubclasses other thanRuntimeException, e.g.,IOException,SQLException): Verified at compile time; the caller must catch them or declarethrows. Used for recoverable external conditions (missing files, network drops). - Unchecked Exceptions (
RuntimeExceptionsubclasses, e.g.,NullPointerException,ArithmeticException,IllegalArgumentException): Not checked at compile time; typically indicate programmer bugs or invalid arguments.
try-with-resources vs. try-finally: In a classic try-finally, forgetting close() or throwing an exception inside close() can mask the original exception. With try (BufferedReader br = new BufferedReader(...)), Java automatically calls close() on any AutoCloseable resource when exiting the block and attaches any closing exception as a suppressed exception rather than losing the primary exception.
Checked exceptions (IOException, SQLException) are enforced by the compiler via try-catch or throws, whereas unchecked exceptions (RuntimeException subclasses like NullPointerException) are not. try-with-resources automatically closes AutoCloseable resources in reverse order and preserves primary exceptions via suppressed exceptions.
Write a Java Streams API expression using List.of(2, 3, 4, 5, 6) that filters for even numbers, squares each remaining number, and calculates the sum of the squared values. Trace each intermediate step and state the final output.
Java Stream Expression:
int result = List.of(2, 3, 4, 5, 6).stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * n)
.sum();Element-by-Element Stream Trace:
- Input stream:
2, 3, 4, 5, 6. - After
.filter(n -> n % 2 == 0):2, 4, 6. - After
.mapToInt(n -> n * n):2*2 = 4,4*4 = 16,6*6 = 36. - After
.sum():4 + 16 + 36 = 56.
The stream retains [2, 4, 6], maps them to squares [4, 16, 36], and .sum() returns 56.
Define a Java record and a sealed class/interface with an example. Using sealed interface Polygon permits Rect, Triangle with records Rect(int w, int h) and Triangle(int a, int b, int c), write a perimeter(Polygon p) method using Java 21 pattern matching switch, and compute the perimeters of Rect(12, 8) and Triangle(3, 5, 4).
Definitions:
- A record is a concise, immutable data class (
record Point(int x, int y) {}) that auto-generatesprivate finalfields, a canonical constructor, component accessors,equals(),hashCode(), andtoString(). - A sealed type (
sealed interface ... permits ...) restricts its direct subtypes to an explicit list, enabling exhaustive compile-time checking inswitchexpressions.
Implementation and Evaluation:
public sealed interface Polygon permits Rect, Triangle {}
public record Rect(int w, int h) implements Polygon {}
public record Triangle(int a, int b, int c) implements Polygon {}
static int perimeter(Polygon p) {
return switch (p) {
case Rect r -> 2 * (r.w() + r.h());
case Triangle t -> t.a() + t.b() + t.c();
};
}perimeter(new Rect(12, 8)) = 2 * (12 + 8) = 2 * 20 = 40.perimeter(new Triangle(3, 5, 4)) = 3 + 5 + 4 = 12.
A record defines an immutable data carrier with auto-generated constructor, accessors, equals, hashCode, and toString; a sealed interface/class restricts permitted subtypes with permits. Using pattern-matching switch, Rect(12, 8) has perimeter 40 and Triangle(3, 5, 4) has perimeter 12.