Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

☕ Chapter 25 — Java Programming Language

Complete reference for Java core packages — classes, methods, collections, streams, I/O, networking and concurrency with ready-to-compile examples.
Part of The Direct Path to Linux Ubuntu — free for all students and developers.

5Packages
166+Symbols
5Examples
javacCompile
Java 21Version
FreeNo login
☕ Core Language 📦 Collections & Utils 📁 File I/O 🌊 Streams API 🌐 Networking ⚡ Examples

☕ Core Language

☕ java.langCore language classes — String, Math, System, Object

📦 Collections & Utils

📦 java.utilCollections, Date/Time, Optional, Random, Scanner

📁 File I/O

📁 java.ioFile I/O — streams, readers, writers, serialization

🌊 Streams API

🌊 java.util.streamStreams API — filter, map, reduce, collect (Java 8+)

🌐 Networking

🌐 java.netNetworking — HTTP client, URL, sockets (Java 11+)

⚡ Quick Copy-Paste Examples

Save each class in a file matching its class name (e.g. Hello.java), compile with javac Hello.java, run with java Hello.

Hello, Java World!

Classic first Java program with a method.

public class Hello {
    static String greet(String name) {
        return String.format("Hello, %s! Welcome to Java.", name);
    }
    public static void main(String[] args) {
        System.out.println(greet("MyWebUniversity"));
        System.out.println(greet("World"));
        System.out.printf("Java version: %s%n",
            System.getProperty("java.version"));
    }
}
// javac Hello.java && java Hello

OOP — Classes, Inheritance & Polymorphism

Abstract classes, method overriding, and polymorphic dispatch.

import java.util.*;

abstract class Shape {
    abstract double area();
    abstract double perimeter();
    String name() { return getClass().getSimpleName(); }
    @Override public String toString() {
        return String.format("%-12s area=%-10.3f perim=%.3f",
            name(), area(), perimeter());
    }
}

class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    @Override double area()      { return Math.PI * r * r; }
    @Override double perimeter() { return 2 * Math.PI * r; }
}

class Rectangle extends Shape {
    double w, h;
    Rectangle(double w, double h) { this.w = w; this.h = h; }
    @Override double area()      { return w * h; }
    @Override double perimeter() { return 2 * (w + h); }
}

public class OOPDemo {
    public static void main(String[] args) {
        List<Shape> shapes = List.of(
            new Circle(5), new Rectangle(4, 6),
            new Circle(2.5), new Rectangle(10, 3));
        shapes.forEach(System.out::println);
        shapes.stream()
              .max(Comparator.comparingDouble(Shape::area))
              .ifPresent(s -> System.out.println("Largest: " + s));
    }
}
// javac OOPDemo.java && java OOPDemo

Generics & Lambda Expressions

Generic class, functional interfaces, and lambda syntax.

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

class Pair<A, B> {
    final A first; final B second;
    Pair(A first, B second) { this.first = first; this.second = second; }
    @Override public String toString() { return "(" + first + ", " + second + ")"; }
    Pair<B, A> swap() { return new Pair<>(second, first); }
}

public class GenericsLambda {
    static <T extends Comparable<T>> T findMax(List<T> list) {
        return list.stream().max(Comparator.naturalOrder()).orElseThrow();
    }

    public static void main(String[] args) {
        // Generic class
        Pair<String, Integer> p = new Pair<>("Go", 24);
        System.out.println(p + " swapped: " + p.swap());

        // Lambdas as Comparators
        List<String> langs = new ArrayList<>(
            Arrays.asList("Python","Java","Go","Rust","Ruby","Perl"));
        langs.sort(Comparator.comparingInt(String::length)
                             .thenComparing(Comparator.naturalOrder()));
        System.out.println("By length: " + langs);

        // Function, Predicate, Consumer, Supplier
        Function<String, Integer> len  = String::length;
        Predicate<String> longWord     = s -> s.length() > 4;
        Consumer<String>  printer      = s -> System.out.println("  " + s);
        Supplier<List<String>> factory = ArrayList::new;

        langs.stream().filter(longWord).map(s -> s + "(" + len.apply(s) + ")")
             .forEach(printer);

        // Generic method
        System.out.println("Max lang: " + findMax(langs));
        System.out.println("Max int : " + findMax(List.of(3,1,4,1,5,9,2,6)));
    }
}
// javac GenericsLambda.java && java GenericsLambda

Exception Handling & try-with-resources

Checked/unchecked exceptions, custom exceptions, and AutoCloseable.

import java.io.*;
import java.nio.file.*;

class DatabaseException extends Exception {
    final int code;
    DatabaseException(String msg, int code) { super(msg); this.code = code; }
}

class FakeConnection implements AutoCloseable {
    final String url;
    FakeConnection(String url) throws DatabaseException {
        if (url == null || url.isEmpty())
            throw new DatabaseException("Empty URL", 1001);
        this.url = url;
        System.out.println("  [connected to " + url + "]");
    }
    String query(String sql) { return "Result of: " + sql; }
    @Override public void close() { System.out.println("  [connection closed]"); }
}

public class ExceptionDemo {
    static int safeDivide(int a, int b) {
        if (b == 0) throw new ArithmeticException("Division by zero");
        return a / b;
    }

    public static void main(String[] args) {
        // Basic exception handling
        for (int[] pair : new int[][]{{10,2},{5,0},{9,3}}) {
            try {
                System.out.printf("%d / %d = %d%n",
                    pair[0], pair[1], safeDivide(pair[0], pair[1]));
            } catch (ArithmeticException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }

        // try-with-resources (AutoCloseable)
        try (FakeConnection conn = new FakeConnection("jdbc:mysql://localhost/mydb")) {
            System.out.println(conn.query("SELECT * FROM students"));
        } catch (DatabaseException e) {
            System.out.printf("DB error %d: %s%n", e.code, e.getMessage());
        }

        // multi-catch
        for (String s : new String[]{"42", "abc", null}) {
            try {
                int val = Integer.parseInt(s);
                System.out.println("Parsed: " + val);
            } catch (NumberFormatException | NullPointerException e) {
                System.out.println("Cannot parse: " + s + " (" + e.getClass().getSimpleName() + ")");
            }
        }
    }
}
// javac ExceptionDemo.java && java ExceptionDemo

Multithreading with ExecutorService

Thread pools, Callable, Future, and concurrent collections.

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

public class ThreadsDemo {
    // AtomicInteger for lock-free counter
    static AtomicInteger counter = new AtomicInteger(0);

    static int computeSquare(int n) throws InterruptedException {
        Thread.sleep(50);  // simulate work
        counter.incrementAndGet();
        return n * n;
    }

    public static void main(String[] args) throws Exception {
        int numCores = Runtime.getRuntime().availableProcessors();
        ExecutorService pool = Executors.newFixedThreadPool(numCores);

        System.out.println("Available processors: " + numCores);

        // Submit Callable tasks
        List<Future<Integer>> futures = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            final int n = i;
            futures.add(pool.submit(() -> computeSquare(n)));
        }

        // Collect results
        List<Integer> results = new ArrayList<>();
        for (Future<Integer> f : futures)
            results.add(f.get());  // blocks until result ready

        System.out.println("Squares: " + results);
        System.out.println("Tasks completed: " + counter.get());

        // ConcurrentHashMap — thread-safe map
        ConcurrentHashMap<String, Integer> safeMap = new ConcurrentHashMap<>();
        List<Future<?>> writes = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            final int n = i;
            writes.add(pool.submit(() ->
                safeMap.merge("key" + (n % 5), 1, Integer::sum)));
        }
        for (Future<?> f : writes) f.get();
        System.out.println("ConcurrentMap: " + new TreeMap<>(safeMap));

        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("All done.");
    }
}
// javac ThreadsDemo.java && java ThreadsDemo