PadhaikoAll subjects

Java Fundamentals

Java Programming (ENCT 327)

Open in the Padhaiko app

1.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.

Java Compilation and Execution PipelineText
Source (.java) ──[ javac ]──> Bytecode (.class) ──[ JVM ]──> Native Machine Code
                                                      ├── ClassLoader Subsystem
                                                      ├── Runtime Data Areas
                                                      └── Execution Engine (Interpreter + JIT + GC)

JDK, JRE, and JVM

Definition

JVM, JRE, and JDK

  1. 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.
  2. JRE (Java Runtime Environment): The software package required to run compiled Java applications. Formally, JRE = JVM + Core Class Libraries (such as java.lang, java.util, java.io, and supporting configuration files).
  3. JDK (Java Development Kit): The complete software kit required to develop, compile, debug, and run Java applications. Formally, JDK = JRE + Development Tools (javac compiler, jar archiver, javadoc generator, jdb debugger, jshell, and profiling utilities).
Comparison of JVM, JRE, and JDK
ComponentPrimary RoleContainsPlatform DependencyTypical User
JVMExecutes .class bytecodeClassLoader, Runtime Memory Areas, Interpreter, JIT, GCPlatform-dependentRuntime engine (internal)
JRERuns existing Java programsJVM + Standard API libraries (rt.jar / modular JRT image)Platform-dependentEnd users running Java apps
JDKDevelops and runs Java programsJRE + javac, jar, javadoc, jdb, jshellPlatform-dependentJava software developers

Internal Architecture of the JVM

  1. ClassLoader Subsystem: Performs three sequential phases for .class files:
    • 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.
  2. 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.
  3. 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).

Major Milestones in the Evolution of Java
ReleaseYearTypeKey Language & Platform Features
Java 1.0 / 1.11995–1997LegacyCore OOP, Applets, AWT, JDBC, JavaBeans, inner classes
Java 5 (1.5)2004MajorGenerics, enhanced for-each loop, autoboxing, enum, varargs, annotations
Java 82014LTSLambda expressions, Streams API, Optional, java.time, default/static interface methods
Java 112018LTSStandard java.net.http.HttpClient, var in lambda parameters, single-file java Foo.java launch
Java 172021LTSRecords, sealed classes, switch expressions, text blocks ("""), pattern matching for instanceof
Java 212023LTSVirtual 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

AspectApache MavenGradle
Configuration FileDeclarative XML (pom.xml)Groovy (build.gradle) or Kotlin (build.gradle.kts) DSL
Core PhilosophyStrict convention over configuration + fixed lifecycle phasesFlexible Directed Acyclic Graph (DAG) of tasks
Build PerformanceRe-runs phases unless configured otherwiseIncremental builds, build cache, persistent daemon
CoordinatesgroupId, artifactId, version (GAV)Same Maven Central GAV coordinates (implementation("..."))
Wrapper Scriptmvnw / mvnw.cmd (optional)gradlew / gradlew.bat (standard, pins Gradle version)

Modern IDEs: IntelliJ IDEA and VS Code

  1. 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).
  2. 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)

Definition

The Four Pillars of OOP in Java

  1. Encapsulation: Bundling data (fields) and behavior (methods) inside a class while hiding internal state with private fields and exposing controlled public getters/setters or domain methods.
  2. 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).
  3. 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).
  4. Abstraction: Hiding implementation details and exposing essential contracts via abstract classes (partial implementation, can hold instance state) and interfaces (pure behavior contracts, plus default and static methods 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.

Core Java Collections and Their Characteristics
InterfaceImplementationOrderingDuplicatesNull Keys/ElementsTypical Time Complexity
List<E>ArrayListInsertion order (indexed)AllowedAllowedget(i) O(1), add amortized O(1)
List<E>LinkedListInsertion orderAllowedAllowedget(i) O(n), head/tail add/remove O(1)
Set<E>HashSetUnorderedNo1 nulladd/contains/remove O(1) average
Set<E>LinkedHashSetInsertion orderNo1 nullO(1) average
Set<E>TreeSetSorted (Comparable/Comparator)NoNo nullO(log n) (Red-Black tree)
Map<K,V>HashMapUnorderedUnique keys1 null keyget/put O(1) average
Map<K,V>TreeMapSorted by keyUnique keysNo null keyO(log n)
Queue<E>ArrayDequeFIFO / DequeAllowedNo nullO(1) amortized at both ends

Exception Handling

All exceptions inherit from java.lang.Throwable, which splits into Error (serious JVM failures like OutOfMemoryError, not normally caught) and Exception:

Java
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; }.

Core Built-in Functional Interfaces (java.util.function)
InterfaceAbstract Method SignaturePurposeExample Lambda
Predicate<T>boolean test(T t)Boolean condition / filters -> s.length() > 3
Function<T, R>R apply(T t)Transform T into RString::toUpperCase (method ref)
Consumer<T>void accept(T t)Side-effect action, no returnSystem.out::println
Supplier<T>T get()Lazy value factory, no inputArrayList::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:

  1. Source: list.stream(), Arrays.stream(arr), Stream.of(...).
  2. Intermediate Operations (lazy, return a new Stream): filter(Predicate), map(Function), flatMap(...), sorted(...), distinct(), limit(n).
  3. Terminal Operations (trigger execution, produce result or side effect): collect(Collectors.toList()) / .toList() (Java 16+), reduce(identity, accumulator), count(), sum() (on IntStream), findFirst() (returns Optional<T>), forEach(Consumer).
Java
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:

Java
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:

Java
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:

Java
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

Example 1.1

1.1

Consider a Java record Order(String category, int qty, double unitPrice) {} and the following list of orders:

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:

Java
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.

Answer:

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.

Example 1.2

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):

Java
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, so netAmount = 2000.0 - 50.0 = 1950.0.
  • Combined sum = 1200.0 + 1950.0 = 3150.0.
Answer:

CashPayment(1200.0) yields 1200.0 and CardPayment(2000.0, 0.025) yields 1950.0, giving a combined net amount of 3150.0.

Example 1.3

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:

  1. State that the JVM initially interprets bytecode instructions sequentially for fast startup.
  2. 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.
Answer:

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

Question 1

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 .class bytecode, 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".

Answer:

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.

Question 2

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.

Answer:

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.

Question 3

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 (Exception subclasses other than RuntimeException, e.g., IOException, SQLException): Verified at compile time; the caller must catch them or declare throws. Used for recoverable external conditions (missing files, network drops).
  • Unchecked Exceptions (RuntimeException subclasses, 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.

Answer:

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.

Question 4

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:

Java
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.
Answer:

The stream retains [2, 4, 6], maps them to squares [4, 16, 36], and .sum() returns 56.

Question 5

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-generates private final fields, a canonical constructor, component accessors, equals(), hashCode(), and toString().
  • A sealed type (sealed interface ... permits ...) restricts its direct subtypes to an explicit list, enabling exhaustive compile-time checking in switch expressions.

Implementation and Evaluation:

Java
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.
Answer:

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.

Java I/O and Data Handling →