DEV Community

Vivek Nishant
Vivek Nishant

Posted on

Crash Course : Core Java

Complete Core Java Tutorial — All Topics with Examples

A full end-to-end Core Java tutorial. Each section is self-contained with runnable examples.


📚 Table of Contents

  1. Basics & Syntax
  2. Variables, Data Types & Wrappers
  3. Operators
  4. Control Flow
  5. Arrays & Varargs
  6. Strings
  7. OOP — Classes & Objects
  8. OOP — 4 Pillars
  9. Keywords (static, final, this, super, instanceof)
  10. Access Modifiers
  11. Packages & Imports
  12. Object Class Methods
  13. Inner Classes
  14. Enums
  15. Interfaces (Advanced) & Functional Interfaces
  16. Abstract Classes
  17. Exceptions
  18. Generics
  19. Collections Framework
  20. Comparable & Comparator
  21. Iterator
  22. Lambda Expressions
  23. Streams API
  24. Optional
  25. Date & Time API
  26. Regular Expressions
  27. File I/O & NIO
  28. Serialization
  29. Multithreading Basics
  30. Concurrency Utilities
  31. Annotations
  32. Reflection
  33. JVM, Memory & Garbage Collection
  34. Modern Java (var, records, sealed, text blocks)
  35. Interview Essentials

1. Basics & Syntax

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Class name = filename (for public class)
  • main = JVM entry point
  • Compile: javac HelloWorld.java → Run: java HelloWorld

2. Variables, Data Types & Wrappers

public class DataTypes {
    public static void main(String[] args) {
        // Primitives
        byte b = 127;              // 1 byte
        short s = 32000;           // 2 bytes
        int i = 100_000;           // 4 bytes
        long l = 8_000_000_000L;   // 8 bytes
        float f = 3.14f;           // 4 bytes
        double d = 3.14159;        // 8 bytes
        char c = 'A';              // 2 bytes
        boolean flag = true;       // 1 bit

        // Wrappers
        Integer boxed = 42;        // autoboxing
        int unboxed = boxed;       // unboxing
        Integer parsed = Integer.parseInt("123");
        Double dbl = Double.valueOf("3.14");

        // Constants
        final double PI = 3.14159;
    }
}
Enter fullscreen mode Exit fullscreen mode

Wrapper classes: Byte, Short, Integer, Long, Float, Double, Character, Boolean


3. Operators

public class Operators {
    public static void main(String[] args) {
        int a = 10, b = 3;

        // Arithmetic
        System.out.println(a + b);  // 13
        System.out.println(a / b);  // 3
        System.out.println(a % b);  // 1

        // Relational
        System.out.println(a > b);  // true
        System.out.println(a == b); // false

        // Logical
        System.out.println(a > 5 && b < 5);  // true
        System.out.println(a > 5 || b > 5);  // true
        System.out.println(!(a > 5));        // false

        // Bitwise
        System.out.println(5 & 3);  // 1
        System.out.println(5 | 3);  // 7
        System.out.println(5 ^ 3);  // 6
        System.out.println(~5);     // -6
        System.out.println(5 << 1); // 10
        System.out.println(5 >> 1); // 2

        // Increment
        int x = 5;
        System.out.println(x++);  // 5, x=6
        System.out.println(++x);  // 7

        // Ternary
        String r = (a > b) ? "a" : "b";
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Control Flow

public class ControlFlow {
    public static void main(String[] args) {
        int score = 85;

        // if-else
        if (score >= 90) System.out.println("A");
        else if (score >= 80) System.out.println("B");
        else System.out.println("C");

        // switch (traditional)
        int day = 2;
        switch (day) {
            case 1: System.out.println("Mon"); break;
            case 2: System.out.println("Tue"); break;
            default: System.out.println("Other");
        }

        // switch expression (Java 14+)
        String type = switch (day) {
            case 1, 7 -> "Weekend";
            case 2, 3, 4, 5, 6 -> "Weekday";
            default -> "Invalid";
        };

        // for
        for (int i = 1; i <= 3; i++) System.out.print(i + " ");

        // while
        int n = 3;
        while (n > 0) { System.out.print(n-- + " "); }

        // do-while (runs at least once)
        int k = 0;
        do { System.out.print(k++ + " "); } while (k < 3);

        // for-each
        int[] arr = {1, 2, 3};
        for (int v : arr) System.out.print(v + " ");

        // break / continue
        for (int i = 0; i < 5; i++) {
            if (i == 2) continue;   // skip
            if (i == 4) break;      // exit
            System.out.print(i + " ");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Arrays & Varargs

import java.util.Arrays;

public class ArrayDemo {
    // Varargs
    static int sum(int... nums) {
        int total = 0;
        for (int n : nums) total += n;
        return total;
    }

    public static void main(String[] args) {
        // 1D
        int[] arr = {5, 2, 8, 1};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));

        // 2D
        int[][] matrix = {{1, 2}, {3, 4}};
        for (int[] row : matrix)
            for (int v : row)
                System.out.print(v + " ");

        // Jagged array
        int[][] jagged = new int[3][];
        jagged[0] = new int[]{1};
        jagged[1] = new int[]{2, 3};

        // Varargs
        System.out.println(sum(1, 2, 3, 4));  // 10
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Strings

public class StringDemo {
    public static void main(String[] args) {
        String s = "Hello World";

        // Common methods
        System.out.println(s.length());                  // 11
        System.out.println(s.charAt(0));                 // H
        System.out.println(s.substring(0, 5));           // Hello
        System.out.println(s.toUpperCase());             // HELLO WORLD
        System.out.println(s.toLowerCase());             // hello world
        System.out.println(s.contains("World"));         // true
        System.out.println(s.startsWith("He"));          // true
        System.out.println(s.endsWith("ld"));            // true
        System.out.println(s.indexOf("o"));              // 4
        System.out.println(s.replace("World", "Java"));  // Hello Java
        System.out.println(s.trim());
        System.out.println(s.split(" ")[0]);             // Hello
        System.out.println(s.equals("Hello World"));     // true
        System.out.println(s.equalsIgnoreCase("HELLO WORLD")); // true
        System.out.println("  ".isBlank());              // true
        System.out.println(String.join("-", "a", "b"));  // a-b

        // String immutability
        String a = "abc";
        a.concat("def");        // "abcdef" discarded
        System.out.println(a);  // abc

        // StringBuilder (fast, mutable)
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 5; i++) sb.append(i).append(",");
        System.out.println(sb);  // 0,1,2,3,4,

        // StringBuffer (thread-safe)
        StringBuffer sbf = new StringBuffer("Hi");
        sbf.append(" there");

        // String pool
        String x = "hi";
        String y = "hi";
        System.out.println(x == y);          // true (pool)
        String z = new String("hi");
        System.out.println(x == z);          // false (new object)
        System.out.println(x.equals(z));     // true
    }
}
Enter fullscreen mode Exit fullscreen mode

Rule: Use StringBuilder in loops, String for constants, StringBuffer for threads.


7. OOP — Classes & Objects

class Student {
    // Fields (encapsulation)
    private String name;
    private int age;

    // Static field
    private static int totalStudents = 0;

    // Constructor
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
        totalStudents++;
    }

    // Copy constructor
    public Student(Student other) {
        this(other.name, other.age);
    }

    // Getters / Setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }

    // Instance method
    public void display() {
        System.out.println(name + ", " + age);
    }

    // Static method
    public static int getTotalStudents() { return totalStudents; }
}

public class OOPDemo {
    public static void main(String[] args) {
        Student s1 = new Student("Alice", 20);
        Student s2 = new Student(s1);
        s1.display();
        System.out.println("Total: " + Student.getTotalStudents());
    }
}
Enter fullscreen mode Exit fullscreen mode

8. OOP — 4 Pillars

8.1 Encapsulation

class Account {
    private double balance;
    public double getBalance() { return balance; }
    public void deposit(double amt) {
        if (amt > 0) balance += amt;
    }
}
Enter fullscreen mode Exit fullscreen mode

8.2 Inheritance

class Animal {
    void sound() { System.out.println("Some sound"); }
}

class Dog extends Animal {
    @Override
    void sound() { System.out.println("Woof"); }
    void fetch() { System.out.println("Fetching"); }
}
Enter fullscreen mode Exit fullscreen mode

8.3 Polymorphism

// Compile-time (overloading)
class MathUtil {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
    int add(int a, int b, int c) { return a + b + c; }
}

// Runtime (overriding)
public class Poly {
    public static void main(String[] args) {
        Animal a = new Dog();  // upcasting
        a.sound();             // Woof (runtime)
    }
}
Enter fullscreen mode Exit fullscreen mode

8.4 Abstraction

abstract class Shape {
    abstract double area();
    void info() { System.out.println("Area = " + area()); }
}

class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    @Override double area() { return Math.PI * r * r; }
}
Enter fullscreen mode Exit fullscreen mode

9. Keywords

public class Keywords {
    static int staticVar = 10;       // shared
    final int FINAL_VAR = 100;       // constant
    String name = "A";
    String name2 = name;             // this.name equivalent

    static { System.out.println("Static block"); }  // runs once

    Keywords() {
        // this() — call another constructor
        this("default");
    }

    Keywords(String name) {
        this.name = name;             // this — refers to current object
    }

    void show() {
        System.out.println(this.name);  // this keyword
    }

    public static void main(String[] args) {
        Object o = "hello";
        if (o instanceof String s) {     // pattern matching
            System.out.println(s.length());
        }
    }
}

class Base { void greet() { System.out.println("Base"); } }
class Child extends Base {
    @Override void greet() {
        super.greet();                 // super — parent method
        System.out.println("Child");
    }
}
Enter fullscreen mode Exit fullscreen mode
Keyword Purpose
static Belongs to class, not instance
final Constant / no override / no inherit
this Current object
super Parent class
instanceof Type check

10. Access Modifiers

Modifier Same Class Same Package Subclass Anywhere
private ✅ ❌ ❌ ❌
default ✅ ✅ ❌ ❌
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅

11. Packages & Imports

package com.myapp.models;

import java.util.List;
import java.util.*;                     // wildcard
import static java.lang.Math.PI;       // static import
import static java.lang.Math.*;        // static wildcard

public class User { }
Enter fullscreen mode Exit fullscreen mode

12. Object Class Methods

class Person {
    String name;
    int age;

    Person(String name, int age) { this.name = name; this.age = age; }

    @Override public String toString() { return name + " (" + age + ")"; }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person p)) return false;
        return age == p.age && name.equals(p.name);
    }

    @Override public int hashCode() { return 31 * name.hashCode() + age; }
}

public class ObjectDemo {
    public static void main(String[] args) {
        Person p1 = new Person("A", 20);
        Person p2 = new Person("A", 20);
        System.out.println(p1.equals(p2));   // true
        System.out.println(p1.hashCode() == p2.hashCode()); // true
        System.out.println(p1);              // uses toString()
    }
}
Enter fullscreen mode Exit fullscreen mode

Contract: If a.equals(b), then a.hashCode() == b.hashCode().


13. Inner Classes

public class Outer {
    private int x = 10;

    // Member inner
    class Inner {
        void show() { System.out.println(x); }
    }

    // Static nested
    static class StaticNested {
        void show() { System.out.println("Static nested"); }
    }

    void method() {
        // Local
        class Local { void show() { System.out.println("Local"); } }
        new Local().show();

        // Anonymous
        Runnable r = new Runnable() {
            public void run() { System.out.println("Anonymous"); }
        };
        r.run();
    }

    public static void main(String[] args) {
        Outer o = new Outer();
        Outer.Inner in = o.new Inner();
        in.show();
        new Outer.StaticNested().show();
    }
}
Enter fullscreen mode Exit fullscreen mode

14. Enums

enum Day {
    MON, TUE, WED, THU, FRI, SAT, SUN;

    boolean isWeekend() { return this == SAT || this == SUN; }
}

enum Status {
    SUCCESS(200), NOT_FOUND(404), ERROR(500);

    private final int code;
    Status(int code) { this.code = code; }
    int getCode() { return code; }
}

public class EnumDemo {
    public static void main(String[] args) {
        Day d = Day.SAT;
        System.out.println(d.isWeekend());         // true
        System.out.println(d.name());              // SAT
        System.out.println(d.ordinal());           // 5

        for (Day day : Day.values()) System.out.print(day + " ");
        System.out.println(Day.valueOf("MON"));    // MON

        System.out.println(Status.ERROR.getCode()); // 500
    }
}
Enter fullscreen mode Exit fullscreen mode

15. Interfaces (Advanced) & Functional Interfaces

interface Vehicle {
    void start();                             // abstract
    default void stop() { System.out.println("Stopped"); }  // default
    static void info() { System.out.println("Vehicle"); }   // static
}

@FunctionalInterface
interface Calculator { int operate(int a, int b); }

public class InterfaceDemo {
    public static void main(String[] args) {
        Vehicle v = () -> System.out.println("Car started");  // lambda
        v.start();
        v.stop();
        Vehicle.info();

        Calculator add = (a, b) -> a + b;
        Calculator mul = (a, b) -> a * b;
        System.out.println(add.operate(2, 3));  // 5
        System.out.println(mul.operate(2, 3));  // 6
    }
}
Enter fullscreen mode Exit fullscreen mode

Built-in functional interfaces:

Interface Method Purpose
Function<T,R> apply T → R
Predicate<T> test T → boolean
Supplier<T> get () → T
Consumer<T> accept T → void
BiFunction<T,U,R> apply (T,U) → R

16. Abstract Classes vs Interfaces

Feature Abstract Class Interface
Fields Any public static final only
Constructors ✅ ❌
Methods Abstract + concrete Abstract + default + static
Multiple inheritance ❌ ✅
When to use Shared state/code Capability/contract
abstract class Shape {
    abstract double area();
    void show() { System.out.println("Area: " + area()); }
}

interface Drawable { void draw(); }

class Circle extends Shape implements Drawable {
    double r;
    Circle(double r) { this.r = r; }
    @Override double area() { return Math.PI * r * r; }
    @Override public void draw() { System.out.println("O"); }
}
Enter fullscreen mode Exit fullscreen mode

17. Exceptions

// Custom checked exception
class InsufficientBalanceException extends Exception {
    InsufficientBalanceException(String msg) { super(msg); }
}

// Custom unchecked
class InvalidAgeException extends RuntimeException {
    InvalidAgeException(String msg) { super(msg); }
}

public class ExceptionDemo {
    static void withdraw(double bal, double amt) throws InsufficientBalanceException {
        if (amt > bal) throw new InsufficientBalanceException("Low balance");
        System.out.println("Withdrawn: " + amt);
    }

    public static void main(String[] args) {
        try {
            withdraw(100, 500);
        } catch (InsufficientBalanceException e) {
            System.out.println("Caught: " + e.getMessage());
        } finally {
            System.out.println("Cleanup");
        }

        // Multi-catch
        try {
            int[] a = new int[2];
            a[5] = 10;
        } catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
            System.out.println("Error: " + e.getClass().getSimpleName());
        }

        // try-with-resources
        try (var reader = new java.io.StringReader("hi")) {
            System.out.println(reader.read());
        } catch (Exception e) { }

        // Nested try
        try {
            try { throw new RuntimeException("inner"); }
            finally { System.out.println("inner finally"); }
        } catch (RuntimeException e) { System.out.println("outer catch"); }
    }
}
Enter fullscreen mode Exit fullscreen mode

Hierarchy: Throwable → Error, Exception → RuntimeException (unchecked) & others (checked).


18. Generics

// Generic class
class Box<T> {
    private T value;
    void set(T v) { value = v; }
    T get() { return value; }
}

// Bounded type
class NumberBox<T extends Number> {
    T value;
    double asDouble() { return value.doubleValue(); }
}

// Generic method
class Util {
    static <T> void printArray(T[] arr) {
        for (T t : arr) System.out.print(t + " ");
    }

    // Wildcards
    static void printList(List<?> list) { }
    static void sumList(List<? extends Number> list) { }
    static void addInt(List<? super Integer> list) { }
}

public class GenericsDemo {
    public static void main(String[] args) {
        Box<String> b = new Box<>();
        b.set("Hello");
        System.out.println(b.get());

        NumberBox<Integer> nb = new NumberBox<>();
        nb.value = 5;
        System.out.println(nb.asDouble());

        Util.printArray(new Integer[]{1, 2, 3});
    }
}
Enter fullscreen mode Exit fullscreen mode

Wildcards: ? extends T (producer) | ? super T (consumer) — PECS principle.


19. Collections Framework

import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        // LIST
        List<String> list = new ArrayList<>();
        list.add("A"); list.add("B"); list.add("A");
        System.out.println(list.get(0));
        System.out.println(list.contains("B"));
        list.remove("A");

        LinkedList<String> ll = new LinkedList<>();
        ll.addFirst("X"); ll.addLast("Y");

        // SET
        Set<Integer> set = new HashSet<>();       // no order
        set.add(1); set.add(2); set.add(1);
        System.out.println(set);                  // [1, 2]

        Set<Integer> linkedSet = new LinkedHashSet<>();  // insertion order
        Set<Integer> treeSet = new TreeSet<>();          // sorted

        // QUEUE / DEQUE
        Queue<Integer> q = new LinkedList<>();
        q.offer(1); q.offer(2);
        System.out.println(q.poll());             // 1

        Deque<Integer> dq = new ArrayDeque<>();
        dq.addFirst(1); dq.addLast(2);

        PriorityQueue<Integer> pq = new PriorityQueue<>();  // min-heap
        pq.offer(5); pq.offer(1); pq.offer(3);
        System.out.println(pq.poll());            // 1

        // MAP
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1); map.put("B", 2);
        System.out.println(map.get("A"));
        System.out.println(map.getOrDefault("Z", 0));
        map.forEach((k, v) -> System.out.println(k + "=" + v));

        TreeMap<String, Integer> tm = new TreeMap<>();      // sorted keys
        LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();  // order

        // Utility class
        Collections.sort(list);
        Collections.reverse(list);
        Collections.max(set);
    }
}
Enter fullscreen mode Exit fullscreen mode
Type Order Duplicates Null Use case
ArrayList insertion ✅ ✅ Fast random access
LinkedList insertion ✅ ✅ Fast insert/delete
HashSet none ❌ ✅ (1) Fast lookup
LinkedHashSet insertion ❌ ✅ (1) Order + uniqueness
TreeSet sorted ❌ ❌ Sorted unique
HashMap none keys ❌ 1 null key Fast KV
TreeMap sorted keys — ❌ Sorted KV
PriorityQueue heap ✅ ❌ Min/max heap

20. Comparable & Comparator

import java.util.*;

class Employee implements Comparable<Employee> {
    String name; int salary;
    Employee(String n, int s) { name = n; salary = s; }

    // Natural ordering by salary
    @Override public int compareTo(Employee e) {
        return Integer.compare(this.salary, e.salary);
    }

    @Override public String toString() { return name + ":" + salary; }
}

public class SortDemo {
    public static void main(String[] args) {
        List<Employee> list = new ArrayList<>(List.of(
            new Employee("A", 5000),
            new Employee("B", 3000),
            new Employee("C", 7000)
        ));

        Collections.sort(list);                     // uses compareTo
        System.out.println(list);

        // Comparator - custom
        list.sort(Comparator.comparing(e -> e.name));
        list.sort(Comparator.comparingInt((Employee e) -> e.salary).reversed());
        list.sort(Comparator.comparing(Employee::getName)
                            .thenComparing(Employee::getSalary));
    }
}
Enter fullscreen mode Exit fullscreen mode

21. Iterator

import java.util.*;

public class IteratorDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("A", "B", "C"));

        // Iterator
        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            String s = it.next();
            if (s.equals("B")) it.remove();  // safe removal
        }

        // ListIterator (bidirectional)
        ListIterator<String> lit = list.listIterator();
        while (lit.hasNext()) lit.next();
        while (lit.hasPrevious()) System.out.print(lit.previous() + " ");

        // for-each uses iterator internally
        for (String s : list) System.out.print(s + " ");
    }
}
Enter fullscreen mode Exit fullscreen mode

22. Lambda Expressions

import java.util.function.*;

public class LambdaDemo {
    public static void main(String[] args) {
        // No params
        Runnable r = () -> System.out.println("Running");
        r.run();

        // One param
        Consumer<String> c = s -> System.out.println(s);
        c.accept("Hi");

        // Multiple params
        BiFunction<Integer, Integer, Integer> sum = (a, b) -> a + b;
        System.out.println(sum.apply(2, 3));

        // Block body
        Function<Integer, Integer> square = n -> {
            int result = n * n;
            return result;
        };

        // Method reference
        Function<String, Integer> len = String::length;
        Supplier<List<String>> listMaker = ArrayList::new;
        BiFunction<Integer, Integer, Integer> maxFn = Math::max;

        // Predicate
        Predicate<Integer> isEven = n -> n % 2 == 0;
        System.out.println(isEven.test(4));  // true
    }
}
Enter fullscreen mode Exit fullscreen mode

23. Streams API

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

public class StreamDemo {
    public static void main(String[] args) {
        List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Filter + map + collect
        List<Integer> evensSquared = nums.stream()
            .filter(n -> n % 2 == 0)
            .map(n -> n * n)
            .collect(Collectors.toList());
        System.out.println(evensSquared);  // [4, 16, 36, 64, 100]

        // Reduce
        int sum = nums.stream().reduce(0, Integer::sum);
        System.out.println(sum);  // 55

        // count, min, max
        long count = nums.stream().filter(n -> n > 5).count();
        Optional<Integer> max = nums.stream().max(Integer::compare);

        // sorted, distinct, limit, skip
        List<Integer> sorted = nums.stream().sorted(Comparator.reverseOrder()).limit(3).collect(Collectors.toList());

        // anyMatch, allMatch, noneMatch
        System.out.println(nums.stream().anyMatch(n -> n > 9));   // true
        System.out.println(nums.stream().allMatch(n -> n > 0));   // true

        // groupingBy
        Map<Boolean, List<Integer>> grouped = nums.stream()
            .collect(Collectors.groupingBy(n -> n % 2 == 0));
        System.out.println(grouped);

        // joining
        String csv = nums.stream().map(String::valueOf).collect(Collectors.joining(","));

        // parallel stream
        long cnt = nums.parallelStream().filter(n -> n % 2 == 0).count();

        // IntStream
        IntStream.range(1, 6).forEach(System.out::print);
        IntStream.rangeClosed(1, 5).sum();

        // flatMap
        List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3, 4));
        List<Integer> flat = nested.stream().flatMap(List::stream).collect(Collectors.toList());
    }
}
Enter fullscreen mode Exit fullscreen mode

24. Optional

import java.util.Optional;

public class OptionalDemo {
    static Optional<String> findName(int id) {
        return id == 1 ? Optional.of("Alice") : Optional.empty();
    }

    public static void main(String[] args) {
        Optional<String> name = findName(1);

        name.ifPresent(System.out::println);
        System.out.println(name.orElse("Unknown"));
        System.out.println(name.orElseGet(() -> "Default"));
        System.out.println(name.map(String::toUpperCase).orElse("N/A"));
        System.out.println(name.filter(s -> s.startsWith("A")).isPresent());

        // orElseThrow
        String n = findName(1).orElseThrow(() -> new RuntimeException("Not found"));
    }
}
Enter fullscreen mode Exit fullscreen mode

25. Date & Time API

import java.time.*;
import java.time.format.DateTimeFormatter;

public class DateTimeDemo {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalTime time = LocalTime.now();
        LocalDateTime dt = LocalDateTime.now();
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

        LocalDate birthday = LocalDate.of(1995, Month.JUNE, 15);
        LocalDate nextWeek = today.plusWeeks(1);
        LocalDate lastMonth = today.minusMonths(1);

        System.out.println(today.isAfter(birthday));
        System.out.println(birthday.getDayOfWeek());
        System.out.println(birthday.lengthOfMonth());

        // Duration / Period
        Duration d = Duration.between(LocalTime.of(10, 0), LocalTime.of(12, 30));
        Period p = Period.between(birthday, today);

        // Format / parse
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
        System.out.println(dt.format(fmt));
        LocalDate parsed = LocalDate.parse("15-06-1995", DateTimeFormatter.ofPattern("dd-MM-yyyy"));

        // Instant (timestamp)
        Instant now = Instant.now();
        System.out.println(now.toEpochMilli());
    }
}
Enter fullscreen mode Exit fullscreen mode

26. Regular Expressions

import java.util.regex.*;

public class RegexDemo {
    public static void main(String[] args) {
        String text = "Contact: alice@example.com, bob@test.org";

        Pattern p = Pattern.compile("[a-z]+@[a-z]+\\.[a-z]+");
        Matcher m = p.matcher(text);
        while (m.find()) System.out.println(m.group());

        // Common methods
        System.out.println("abc123".matches("\\w+"));            // true
        System.out.println("123".replaceAll("\\d", "X"));        // XXX
        System.out.println("a,b,c".split(",").length);           // 3

        // Validate email
        String email = "user@mail.com";
        System.out.println(email.matches("^[\\w.]+@[\\w.]+\\.[a-z]{2,}$"));
    }
}
Enter fullscreen mode Exit fullscreen mode

Common patterns: \\d digit, \\w word, \\s space, . any, * 0+, + 1+, ? optional, {n,m} range, [] class, () group.


27. File I/O & NIO

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

public class FileDemo {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("demo.txt");

        // Write (NIO)
        Files.writeString(path, "Line 1\nLine 2\n");

        // Read (NIO)
        String content = Files.readString(path);
        List<String> lines = Files.readAllLines(path);

        // Stream lines
        Files.lines(path).forEach(System.out::println);

        // Check / delete
        System.out.println(Files.exists(path));
        // Files.delete(path);

        // BufferedWriter (classic)
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"))) {
            bw.write("Hello");
            bw.newLine();
        }

        // BufferedReader (classic)
        try (BufferedReader br = new BufferedReader(new FileReader("out.txt"))) {
            String line;
            while ((line = br.readLine()) != null) System.out.println(line);
        }

        // Byte streams
        try (FileInputStream in = new FileInputStream("out.txt")) {
            int b;
            while ((b = in.read()) != -1) { /* process */ }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

28. Serialization

import java.io.*;

class User implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    transient String password;   // not serialized
    static String role = "user"; // not serialized

    User(String name, String pwd) { this.name = name; this.password = pwd; }
}

public class SerializationDemo {
    public static void main(String[] args) throws Exception {
        User u = new User("Alice", "secret");

        // Serialize
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.ser"))) {
            oos.writeObject(u);
        }

        // Deserialize
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser"))) {
            User restored = (User) ois.readObject();
            System.out.println(restored.name + " / " + restored.password);  // password null
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

29. Multithreading Basics

class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 3; i++)
            System.out.println(Thread.currentThread().getName() + ": " + i);
    }
}

class MyRunnable implements Runnable {
    public void run() { System.out.println("Runnable running"); }
}

public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        MyThread t1 = new MyThread();
        t1.setName("T1");
        t1.start();

        Thread t2 = new Thread(new MyRunnable());
        t2.start();

        // Lambda
        Thread t3 = new Thread(() -> System.out.println("Lambda thread"));
        t3.start();

        // Lifecycle methods
        t1.join();           // wait
        Thread.sleep(100);   // pause

        // Thread states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED

        // Synchronization
        Counter c = new Counter();
        Thread a = new Thread(() -> { for (int i = 0; i < 1000; i++) c.increment(); });
        Thread b = new Thread(() -> { for (int i = 0; i < 1000; i++) c.increment(); });
        a.start(); b.start();
        a.join(); b.join();
        System.out.println(c.getCount());  // 2000
    }
}

class Counter {
    private int count = 0;
    public synchronized void increment() { count++; }  // thread-safe
    public int getCount() { return count; }
}
Enter fullscreen mode Exit fullscreen mode

30. Concurrency Utilities

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

public class ConcurrencyDemo {
    public static void main(String[] args) throws Exception {
        // Thread pool
        ExecutorService pool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 5; i++) {
            pool.submit(() -> System.out.println(Thread.currentThread().getName()));
        }
        pool.shutdown();
        pool.awaitTermination(1, TimeUnit.SECONDS);

        // Callable + Future
        ExecutorService ex = Executors.newSingleThreadExecutor();
        Future<Integer> future = ex.submit(() -> 2 + 3);
        System.out.println(future.get());  // 5
        ex.shutdown();

        // Atomic classes
        AtomicInteger counter = new AtomicInteger(0);
        counter.incrementAndGet();
        counter.compareAndSet(1, 10);

        // Concurrent collections
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        CopyOnWriteArrayList<String> cowList = new CopyOnWriteArrayList<>();
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
        queue.put(1);
        queue.take();

        // Locks
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        try { /* critical section */ }
        finally { lock.unlock(); }

        // CountDownLatch
        CountDownLatch latch = new CountDownLatch(3);
        // ... latch.countDown(); latch.await();
    }
}
Enter fullscreen mode Exit fullscreen mode

31. Annotations

import java.lang.annotation.*;
import java.lang.reflect.*;

// Custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
    String value() default "default";
    int priority() default 1;
}

class Service {
    @MyAnnotation(value = "hello", priority = 5)
    public void doWork() { }

    @Deprecated
    public void oldMethod() { }

    @Override
    public String toString() { return "Service"; }

    @SuppressWarnings("unchecked")
    public void unchecked() { }
}

public class AnnotationDemo {
    public static void main(String[] args) throws Exception {
        Method m = Service.class.getMethod("doWork");
        MyAnnotation ann = m.getAnnotation(MyAnnotation.class);
        System.out.println(ann.value() + " / " + ann.priority());
    }
}
Enter fullscreen mode Exit fullscreen mode

Built-in: @Override, @Deprecated, @SuppressWarnings, @FunctionalInterface, @SafeVarargs


32. Reflection

import java.lang.reflect.*;

class Employee {
    private String name = "Alice";
    public int age = 25;
    public Employee() { }
    public Employee(String name) { this.name = name; }
    public void greet() { System.out.println("Hi " + name); }
    private void secret() { System.out.println("Secret"); }
}

public class ReflectionDemo {
    public static void main(String[] args) throws Exception {
        Class<?> cls = Class.forName("Employee");

        // Fields
        for (Field f : cls.getDeclaredFields())
            System.out.println(f.getName() + " : " + f.getType());

        // Methods
        for (Method m : cls.getDeclaredMethods())
            System.out.println(m.getName());

        // Create instance
        Object obj = cls.getDeclaredConstructor().newInstance();

        // Access private field
        Field nameField = cls.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(obj, "Bob");

        // Invoke method
        Method greet = cls.getMethod("greet");
        greet.invoke(obj);
    }
}
Enter fullscreen mode Exit fullscreen mode

33. JVM, Memory & Garbage Collection

public class MemoryDemo {
    public static void main(String[] args) {
        Runtime rt = Runtime.getRuntime();
        System.out.println("Max: " + rt.maxMemory() / 1024 / 1024 + " MB");
        System.out.println("Total: " + rt.totalMemory() / 1024 / 1024 + " MB");
        System.out.println("Free: " + rt.freeMemory() / 1024 / 1024 + " MB");

        // Trigger GC (hint only)
        System.gc();

        // Create garbage
        for (int i = 0; i < 100000; i++) { Object o = new Object(); }
    }
}
Enter fullscreen mode Exit fullscreen mode

JVM Memory:
| Area | Stores |
|------|--------|
| Heap | Objects, class instances |
| Stack | Method frames, local variables, references |
| Metaspace | Class metadata |
| PC Register | Current instruction |
| Native Stack | Native method calls |

Class Loading: Bootstrap → Extension → Application

GC Collectors: Serial, Parallel, G1, ZGC


34. Modern Java Features

// var (Java 10) - local type inference
var list = new java.util.ArrayList<String>();
var map = new java.util.HashMap<String, Integer>();

// Text blocks (Java 15)
String json = """
    {
        "name": "Alice",
        "age": 25
    }
    """;

// Records (Java 16) - immutable data carriers
record Point(int x, int y) {
    Point { if (x < 0) throw new IllegalArgumentException(); }  // compact ctor
}

// Sealed classes (Java 17)
sealed interface Shape permits Circle, Square { }
record Circle(double r) implements Shape { }
record Square(double s) implements Shape { }

// Pattern matching for instanceof (Java 16)
Object obj = "hello";
if (obj instanceof String s) System.out.println(s.length());

// Pattern matching for switch (Java 21)
String describe(Object o) {
    return switch (o) {
        case Integer i -> "int: " + i;
        case String s -> "str: " + s;
        case null -> "null";
        default -> "unknown";
    };
}

public class ModernJava {
    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p.x() + "," + p.y());  // accessors
        System.out.println(p);                    // auto toString
    }
}
Enter fullscreen mode Exit fullscreen mode

35. Interview Essentials — Quick Reference

Difference Tables

Topic A B
String vs StringBuilder Immutable Mutable
ArrayList vs LinkedList Fast access Fast insert/delete
HashMap vs Hashtable Not sync, 1 null key Sync, no null
== vs equals Reference Content
final vs finally vs finalize Constant Cleanup block
Abstract class vs Interface State + methods Contract only
wait() vs sleep() Releases lock Holds lock
Checked vs Unchecked Compile-time Runtime
Comparator vs Comparable External Internal
throw vs throws Throw exception Declare exception

Common Concepts

  • Immutability: final fields, defensive copies, no setters
  • PECS: Producer extends, Consumer super
  • SOLID principles
  • Fail-fast vs Fail-safe iterators
  • Shallow vs Deep copy
  • Stack vs Heap
  • Method overloading vs overriding

🎯 Suggested Learning Path

Week 1-2 : Sections 1-8    (basics + OOP)
Week 3   : Sections 9-17   (keywords, enums, exceptions, interfaces)
Week 4   : Sections 18-23  (generics, collections, lambdas, streams)
Week 5   : Sections 24-33  (Optional, I/O, concurrency, JVM)
Week 6   : Sections 34-35  (modern Java + interview prep)
Enter fullscreen mode Exit fullscreen mode

💡 Mini Projects to Practice

  1. Bank Management System — OOP + exceptions + collections
  2. Library Management — Comparator + File I/O
  3. Employee CRUD API — Collections + streams
  4. Multi-threaded File Downloader — Concurrency
  5. Student Result Analyzer — Streams + grouping

Top comments (0)