0% found this document useful (0 votes)
3 views50 pages

Java Complete Revision Guide

The document is a comprehensive Java revision guide covering fundamental concepts such as variables, data types, operators, control flow, and object-oriented programming principles including classes, inheritance, and polymorphism. It also addresses advanced topics like exception handling, multithreading, and collections, along with practical interview questions. The guide is structured in chapters, each detailing specific Java features and concepts essential for both beginners and those preparing for interviews.

Uploaded by

sachinyadav62521
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views50 pages

Java Complete Revision Guide

The document is a comprehensive Java revision guide covering fundamental concepts such as variables, data types, operators, control flow, and object-oriented programming principles including classes, inheritance, and polymorphism. It also addresses advanced topics like exception handling, multithreading, and collections, along with practical interview questions. The guide is structured in chapters, each detailing specific Java features and concepts essential for both beginners and those preparing for interviews.

Uploaded by

sachinyadav62521
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

■ JAVA
Complete Revision Guide

From Basics to Advanced · Interview Ready · Logic Building

0 Java Fundamentals Variables, Data Types, Operators, Control Flow


1

0 OOP Concepts Classes, Objects, Inheritance, Polymorphism


2

0 Core Java Features Arrays, Strings, Static, Packages, Access Modifiers


3

0 Advanced OOP Abstract, Interface, Enum, Annotations, Lambda


4

0 Exception Handling try-catch, Custom Exceptions, throws, Resources


5

0 Multithreading Threads, Runnable, Race Conditions, Thread States


6

0 Collections & ArrayList, Set, Map, Comparator, Stream, Lambda


7 Stream API

0 Wrapper Classes Autoboxing, Unboxing, Utility Methods, Caching


8

0 Interview & Practice 80+ Questions with Hints across all Topics
9 Qs

Generated: May 22, 2026


CHAPTER 01

Java Fundamentals
Variables · Data Types · Operators · Control Flow · Loops

1.1 How Java Works — JDK / JRE / JVM

Java follows a Write Once, Run Anywhere philosophy. Source code (.java) is compiled by javac into
platform-independent bytecode (.class). The JVM then interprets/JIT-compiles that bytecode on the
target OS.

Compon Full Form Role


ent

JDK Java javac compiler + JRE + dev tools. Used by developers.


Development
Kit

JRE Java Runtime JVM + libraries. Required to run Java programs.


Environment

JVM Java Virtual Executes bytecode. Platform-specific but bytecode is universal.


Machine

TIP
JDK ⊃ JRE ⊃ JVM — each is a subset of the previous one.

1.2 Variables

A variable is a named memory location that holds a value. Java is statically typed — every variable must
have a declared type.

Local Variable Instance Variable Static Variable

Local: declared inside a method — no default value, must initialize before use.

Instance: declared inside a class but outside methods — each object gets its own copy.

Static: belongs to the class — shared across all objects.

Java Complete Revision Guide Page 2


Variables

int age = 25; // local variable


double salary = 75000.50; // local variable

class Student {
String name; // instance variable (default null)
int rollNo; // instance variable (default 0)
static int count = 0; // static / class variable
}

1.3 Primitive Data Types

Type Size Default Range / Notes

byte 1 byte 0 -128 to 127

short 2 bytes 0 -32,768 to 32,767

int 4 bytes 0 -2^31 to 2^31-1 (~2.1 billion)

long 8 bytes 0L -2^63 to 2^63-1 — suffix L

float 4 bytes 0.0f ~7 decimal digits — suffix f

double 8 bytes 0.0d ~15 decimal digits (default for decimals)

char 2 bytes \u0000 Unicode — single quotes: 'A'

boolean 1 bit false true or false only

INFO
Non-primitive (Reference) types: String, Array, Class, Interface — store references
(addresses), not actual values.

1.4 Literals

A literal is a fixed value written directly in code.

Literals

int decimal = 100;


int octal = 0144; // prefix 0
int hex = 0x64; // prefix 0x
int binary = 0b1100100; // prefix 0b (Java 7+)
long big = 10_000_000L; // underscores for readability (Java 7+)
double d = 1.5e3; // 1500.0 scientific notation
char c = 'A';
String s = "Hello";
boolean flag = true;

Java Complete Revision Guide Page 3


1.5 Type Conversion & Casting

Widening (Implicit): Smaller type automatically fits into larger type. Safe — no data loss.

Narrowing (Explicit): Larger type into smaller — must cast manually. May lose data.

Type Conversion

// Widening — automatic
int i = 100;
long l = i; // int -> long (OK)
float f = l; // long -> float (OK)

// Narrowing — explicit cast required


double d = 9.99;
int x = (int) d; // x = 9 (decimal part lost!)

// Type promotion in expressions


byte b1 = 10, b2 = 20;
int result = b1 + b2; // promoted to int automatically

TIP
Widening order: byte → short → int → long → float → double

1.6 Operators

Assignment Operators

Assignment Ops

int a = 10;
a += 5; // a = 15 (a = a + 5)
a -= 3; // a = 12
a *= 2; // a = 24
a /= 4; // a = 6
a %= 4; // a = 2 (remainder)

Relational Operators
Operator Meaning Example

== Equal to a == b

!= Not equal a != b

> Greater than a>b

< Less than a<b

>= Greater or equal a >= b

Java Complete Revision Guide Page 4


Operator Meaning Example

<= Less or equal a <= b

Logical Operators

Operator Symb Example Returns true when


ol

AND && a>0 && b>0 Both conditions true

OR || a>0 || b>0 At least one true

NOT ! !flag flag is false

1.7 Control Flow — if / else / switch / ternary

Control Flow

// if-else if-else
int marks = 75;
if (marks >= 90) [Link]("A");
else if (marks >= 75) [Link]("B");
else if (marks >= 60) [Link]("C");
else [Link]("Fail");

// Ternary operator
String result = (marks >= 60) ? "Pass" : "Fail";

// Switch statement
int day = 3;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Other");
}

INFO
Switch works with: byte, short, int, char, String (Java 7+), and Enum.

1.8 Loops

Java Complete Revision Guide Page 5


Loops

// while loop — condition checked first


int i = 1;
while (i <= 5) { [Link](i+" "); i++; }

// do-while — executes at least once


int j = 1;
do { [Link](j+" "); j++; } while (j <= 5);

// for loop — compact init/condition/update


for (int k = 1; k <= 5; k++) { [Link](k+" "); }

// Enhanced for (for-each) — iterates collections/arrays


int[] nums = {10, 20, 30};
for (int n : nums) { [Link](n); }

// break and continue


for (int n = 1; n <= 10; n++) {
if (n == 5) continue; // skip 5
if (n == 8) break; // stop at 8
[Link](n+" ");
}

Loop Use When

while Number of iterations unknown; condition checked before entry

do-while Must execute at least once regardless of condition

for Number of iterations known in advance

for-each Iterating arrays or collections without index needed

Java Complete Revision Guide Page 6


CHAPTER 02

OOP Concepts
Class · Object · Encapsulation · Inheritance · Polymorphism · Abstraction

2.1 Class and Object

Class: A blueprint/template that defines properties (fields) and behaviours (methods).

Object: A real-world instance of a class created using the new keyword. Stored in Heap memory.

Class & Object

class Car {
// Fields (instance variables)
String brand;
int speed;

// Method
void drive() {
[Link](brand + " driving at " + speed + " km/h");
}
}

public class Main {


public static void main(String[] args) {
Car c1 = new Car(); // Object created on Heap
[Link] = "Toyota";
[Link] = 120;
[Link](); // Toyota driving at 120 km/h
}
}

TIP
Stack holds the reference variable. Heap holds the actual object.

2.2 Constructors

A constructor is a special method called automatically when an object is created. It has the same name
as the class and no return type.

Java Complete Revision Guide Page 7


Constructors

class Student {
String name;
int age;

// Default constructor (no-arg)


Student() {
name = "Unknown"; age = 0;
}

// Parameterized constructor
Student(String n, int a) {
[Link] = n; // this refers to current object
[Link] = a;
}

// Constructor chaining using this()


Student(String n) {
this(n, 18); // calls Student(String, int)
}
}

CAUTION
If you define any constructor, Java no longer provides the default constructor.

2.3 this Keyword

this refers to the current class instance. Used to:

• Refer to current class instance variable (resolve ambiguity)


• Invoke current class method or constructor — this()
• Pass current object as argument to another method

2.4 Encapsulation

Bundling data (fields) and methods together, and hiding internal details using access modifiers.
Achieved using private fields + public getters/setters.

Java Complete Revision Guide Page 8


Encapsulation

class BankAccount {
private double balance; // hidden from outside

public double getBalance() { return balance; }

public void deposit(double amt) {


if (amt > 0) balance += amt;
}

public void withdraw(double amt) {


if (amt > 0 && amt <= balance) balance -= amt;
else [Link]("Insufficient funds");
}
}

2.5 Inheritance

Inheritance allows a child class to acquire properties and methods of a parent class using the extends
keyword. Promotes code reuse.

Type Description Java Support

Single One child extends one parent Yes

Multilevel Chain: A → B → C Yes

Hierarchical Multiple children from one parent Yes

Multiple One child from multiple parents NO (use Interface)

Hybrid Combination NO (use Interface)

Java Complete Revision Guide Page 9


Inheritance

class Animal {
String name;
void eat() { [Link](name+" eats"); }
void sleep(){ [Link](name+" sleeps"); }
}

class Dog extends Animal {


void bark() { [Link](name+" barks"); }
}

// super keyword — access parent class


class Puppy extends Dog {
Puppy(String n) {
[Link] = n; // access parent field
}
void show() {
[Link](); // call parent method
}
}

IMPORTANT
super() must be the FIRST statement in a constructor if used.

2.6 Method Overriding

Redefining a parent class method in a child class with the same name and signature. Enables runtime
polymorphism.

Overriding

class Shape {
double area() { return 0; }
}

class Circle extends Shape {


double radius;
Circle(double r) { [Link] = r; }

@Override
double area() { return [Link] * radius * radius; }
}

class Rectangle extends Shape {


double l, w;
Rectangle(double l, double w) { this.l=l; this.w=w; }

@Override
double area() { return l * w; }
}

Java Complete Revision Guide Page 10


Overloading Overriding

Where Same class Parent + Child class

Signature Different parameters Same name + parameters

Return type Can differ Must be same (or covariant)

Time Compile time Runtime

Static methods Can overload Cannot override (hidden)

2.7 Polymorphism & Dynamic Method Dispatch

Compile-time polymorphism: Method Overloading — resolved at compile time.

Runtime polymorphism: Method Overriding — resolved at runtime via Dynamic Method Dispatch.

Polymorphism

// Dynamic Method Dispatch


Shape s;
s = new Circle(5); // parent reference → child object
[Link]([Link]()); // calls [Link]() at runtime

s = new Rectangle(4, 6);


[Link]([Link]()); // calls [Link]() at runtime

// Upcasting (implicit)
Animal a = new Dog(); // OK — Dog IS-A Animal

// Downcasting (explicit)
Dog d = (Dog) a; // must cast explicitly; may throw ClassCastException
if (a instanceof Dog) { // safe check first!
Dog d2 = (Dog) a;
}

2.8 Abstract Class & Abstract Methods

Abstract class cannot be instantiated directly. Contains abstract methods (no body) that must be
implemented by subclasses.

Java Complete Revision Guide Page 11


Abstract Class

abstract class Vehicle {


String type;
abstract void fuelType(); // must override in subclass
void start() { [Link]("Starting..."); } // concrete method
}

class ElectricCar extends Vehicle {


@Override
void fuelType() { [Link]("Electric"); }
}

// Vehicle v = new Vehicle(); ERROR — cannot instantiate


Vehicle v = new ElectricCar(); // OK — polymorphism
[Link]();

IMPORTANT
A class with even ONE abstract method must be declared abstract.

2.9 final Keyword

Context Effect

final variable Becomes a constant — value cannot change

final method Cannot be overridden in subclass

final class Cannot be extended (e.g., String, Integer, Math)

final Keyword

final double PI = 3.14159; // constant


// PI = 3.0; ERROR

final class Immutable { }


// class Sub extends Immutable { } ERROR

Java Complete Revision Guide Page 12


CHAPTER 03

Core Java Features


Arrays · Strings · Static · Packages · Access Modifiers · Object Class

3.1 Arrays

An array stores multiple values of the same type in contiguous memory. Fixed size once created.

Arrays

// 1D Array
int[] arr = new int[5]; // default values 0
int[] arr2 = {10, 20, 30, 40, 50}; // array literal
[Link](arr2[0]); // 10
[Link]([Link]); // 5

// 2D Array
int[][] matrix = new int[3][3];
int[][] m2 = {{1,2,3},{4,5,6},{7,8,9}};

// Jagged Array (rows of different lengths)


int[][] jagged = new int[3][];
jagged[0] = new int[1];
jagged[1] = new int[2];
jagged[2] = new int[3];

// Array of Objects
Student[] students = new Student[3];
students[0] = new Student("Sachin", 22);

CAUTION
Arrays have fixed size — use ArrayList when you need dynamic sizing.

3.2 Strings

String Pool: String literals are stored in the String Pool (inside Heap). Same literal reuses the same
object.

Immutability: String objects cannot be changed — any operation creates a new String.

Java Complete Revision Guide Page 13


String Methods

String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

[Link](s1 == s2); // true (same pool object)


[Link](s1 == s3); // false (new object in heap)
[Link]([Link](s3)); // true (always use equals!)

// Common String methods


[Link]() // 5
[Link](0) // H
[Link]("l") // 2
[Link](1, 3) // el
[Link]() // HELLO
[Link]() // hello
[Link]() // removes leading/trailing spaces
[Link]("l","r") // Herro
[Link]("ell") // true
[Link](",") // String array
"".isEmpty() // true

StringBuffer vs StringBuilder

Feature String StringBuffer StringBuilder

Mutability Immutable Mutable Mutable

Thread-safety Yes Yes No


(immutable) (synchronized)

Performance Slow (new Medium Fast


object)

Use when Constant Multi-thread Single-thread


values

StringBuilder

StringBuilder sb = new StringBuilder("Hello");


[Link](" World"); // Hello World
[Link](5, ","); // Hello, World
[Link](); // dlroW ,olleH
[Link](0, 3); // removes chars 0-2
[Link]([Link]());

3.3 Static Keyword

static members belong to the class, not to any object. Loaded when the class is loaded (before main
runs).

Java Complete Revision Guide Page 14


Static

class Counter {
static int count = 0; // shared by ALL objects

// Static block — runs ONCE when class is loaded


static {
[Link]("Class loaded!");
count = 100;
}

Counter() { count++; }

// Static method — can only access static members directly


static int getCount() { return count; }
}

[Link](); // no object needed

CAUTION
Static methods CANNOT use this or super. They cannot access instance variables directly.

3.4 Packages & Access Modifiers

A package is a namespace that organizes related classes. Use import to bring in classes from other
packages.

Modifier Same Class Same Subclass Anywhere


Package

private ✓ ✗ ✗ ✗

default (no keyword) ✓ ✓ ✗ ✗

protected ✓ ✓ ✓ ✗

public ✓ ✓ ✓ ✓

3.5 Object Class — equals(), toString(), hashCode()

Every class in Java implicitly extends [Link]. Key methods to override:

Java Complete Revision Guide Page 15


Object Class Methods

class Point {
int x, y;
Point(int x, int y) { this.x=x; this.y=y; }

@Override
public String toString() {
return "Point(" + x + ", " + y + ")";
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}

@Override
public int hashCode() {
return 31 * x + y; // common formula
}
}

IMPORTANT
Contract: if [Link](b) is true, [Link]() must equal [Link](). Always override both
together.

3.6 Inner Classes & Anonymous Inner Classes

Java Complete Revision Guide Page 16


Inner & Anonymous

// Inner class — access outer class members


class Outer {
int x = 10;
class Inner {
void show() { [Link]("x = " + x); }
}
}
Outer o = new Outer();
[Link] i = [Link] Inner();
[Link]();

// Anonymous Inner Class — one-time use


abstract class Greeting {
abstract void greet();
}
Greeting g = new Greeting() {
@Override
public void greet() { [Link]("Hello!"); }
};
[Link]();

Java Complete Revision Guide Page 17


CHAPTER 04

Advanced OOP
Interface · Enum · Annotations · Lambda · Functional Interface

4.1 Interface

An interface is a contract — it defines WHAT a class should do, not HOW. All methods are public
abstract by default (pre-Java 8). Solves multiple inheritance.

Interface

interface Drawable {
void draw(); // public abstract by default
double area();

// Default method (Java 8+)


default void describe() {
[Link]("This is a drawable shape");
}

// Static method (Java 8+)


static void info() {
[Link]("Interface: Drawable");
}
}

interface Colorable {
void setColor(String c);
}

// Multiple interface implementation


class Triangle implements Drawable, Colorable {
private double base, height;
private String color;
Triangle(double b, double h) { base=b; height=h; }

@Override public void draw() { [Link]("Drawing triangle"); }


@Override public double area() { return 0.5 * base * height; }
@Override public void setColor(String c) { color = c; }
}

Feature Abstract Class Interface

Instantiate No No

Constructor Yes No

Fields Any type public static final only

Methods Abstract + Concrete Abstract + default + static

Inheritance Single (extends) Multiple (implements)

Java Complete Revision Guide Page 18


Feature Abstract Class Interface

Speed Faster Slightly slower (resolved at runtime)

Use when Shared base behaviour Contract / capability

4.2 Enum

Enum (enumeration) is a special class with a fixed set of constants. Each constant is an object.

Enum

enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

// Enum with constructor and method


enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6);

private final double mass;


private final double radius;

Planet(double mass, double radius) {


[Link] = mass; [Link] = radius;
}
double surfaceGravity() { return 6.67300E-11*mass/(radius*radius); }
}

// Using enum in switch


Day d = [Link];
switch(d) {
case FRIDAY: [Link]("Weekend soon!"); break;
default: [Link]("Weekday");
}

// Enum methods
[Link]() // array of all constants
[Link]("MONDAY") // get by name
[Link]() // 4 (zero-indexed position)
[Link]() // "FRIDAY"

4.3 Annotations

Annotations provide metadata about code. They don't change program logic but affect how code is
processed by compiler, IDE, or frameworks.

Java Complete Revision Guide Page 19


Annotation Purpose

@Override Tells compiler to verify this overrides a parent method

@Deprecated Marks method/class as outdated; use discouraged

@SuppressWarnings Suppresses specific compiler warnings

@FunctionalInterface Ensures interface has exactly one abstract method

@SafeVarargs Suppresses unchecked warnings on vararg methods

4.4 Functional Interface & Lambda Expression

A Functional Interface has exactly ONE abstract method. Lambda expressions provide a concise way to
implement it.

Lambda

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

// Without Lambda (Anonymous Inner Class)


MathOperation add = new MathOperation() {
public int operate(int a, int b) { return a + b; }
};

// With Lambda — much cleaner!


MathOperation add2 = (a, b) -> a + b;
MathOperation multiply = (a, b) -> a * b;
MathOperation power = (a, b) -> (int) [Link](a, b);

[Link]([Link](5, 3)); // 8
[Link]([Link](5, 3)); // 15

// Lambda with return statement (block body)


MathOperation max = (a, b) -> {
if (a > b) return a;
else return b;
};

Built-in Functional Interfaces ([Link])


Interface Method Example

Predicate boolean test(T t) x -> x > 0

Function R apply(T t) s -> [Link]()

Consumer void accept(T t) s -> [Link](s)

Java Complete Revision Guide Page 20


Interface Method Example

Supplier T get() () -> new ArrayList<>()

BiFunction R apply(T t, U u) (a,b) -> a+b

4.5 Types of Interface

Type Description Example

Normal 2+ abstract methods Comparable, Iterable

Functional / SAM Exactly 1 abstract method Runnable, Callable, Comparator

Marker No methods — tags a class Serializable, Cloneable

Tagging Inherits from another


interface

Java Complete Revision Guide Page 21


CHAPTER 05

Exception Handling
try-catch · Hierarchy · Custom Exceptions · throws · Resources

5.1 What is an Exception?

An exception is an abnormal condition that disrupts normal program flow. Java uses a Throwable
hierarchy.

Error Checked Unchecked Exception


Exception

Package [Link] [Link] RuntimeException


r tion

Recoverable No Yes Yes (but avoidable)

Must handle No Yes No

Examples OutOfMemor IOException, NullPointerException, ArrayIndexOutOfBounds


yError, Stack SQLException
Overflow

5.2 try-catch-finally

try-catch-finally

try {
int[] arr = new int[5];
arr[10] = 1; // throws ArrayIndexOutOfBoundsException
int res = 10 / 0; // throws ArithmeticException
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array error: " + [Link]());
}
catch (ArithmeticException e) {
[Link]("Math error: " + [Link]());
}
catch (Exception e) { // catch-all (must be LAST)
[Link]("General: " + [Link]());
}
finally {
[Link]("Always runs — cleanup here");
}

// Multi-catch (Java 7+)


catch (IOException | SQLException e) { ... }

Java Complete Revision Guide Page 22


IMPORTANT
finally block ALWAYS runs — even if an exception was thrown or return was called. Use it for
cleanup.

5.3 throw vs throws

throw throws

Purpose Explicitly throw an exception Declares possible exceptions

Where used Inside method body In method signature

How many One exception per throw Multiple, comma-separated

Example throw new void m() throws IOException, SQLException


NullPointerException()

throw vs throws

// throw — used inside method


void validateAge(int age) {
if (age < 0) throw new IllegalArgumentException("Age cannot be negative");
if (age > 150) throw new IllegalArgumentException("Invalid age");
}

// throws — duck (defer) exception to caller


void readFile(String path) throws IOException {
FileReader fr = new FileReader(path); // may throw IOException
}

5.4 Custom Exceptions

Java Complete Revision Guide Page 23


Custom Exception

// Checked custom exception


class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds. Short by: " + amount);
[Link] = amount;
}
public double getAmount() { return amount; }
}

// Unchecked custom exception


class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String msg) { super(msg); }
}

// Using custom exception


class BankAccount {
double balance = 1000;
void withdraw(double amt) throws InsufficientFundsException {
if (amt > balance) throw new InsufficientFundsException(amt - balance);
balance -= amt;
}
}

5.5 try-with-resources (Java 7+)

Automatically closes resources (that implement AutoCloseable) when the try block exits — cleaner than
finally for I/O.

try-with-resources

try (FileReader fr = new FileReader("[Link]");


BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
}
// fr and br are automatically closed here — no finally needed!

5.6 User Input — Scanner & BufferedReader

Java Complete Revision Guide Page 24


User Input

// Scanner — easiest for beginners


import [Link];
Scanner sc = new Scanner([Link]);
int n = [Link]();
double d = [Link]();
String s = [Link](); // single word
String l = [Link](); // full line

// BufferedReader — faster for large input


import [Link].*;
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String line = [Link]();
int n2 = [Link]([Link]().trim());

Java Complete Revision Guide Page 25


CHAPTER 06

Multithreading
Threads · Runnable · Priority · Race Condition · Thread States

6.1 What is a Thread?

A thread is the smallest unit of execution within a process. Java supports multithreading natively —
multiple threads can run concurrently sharing the same process memory.

INFO
Process = program in execution. Thread = lightweight sub-process inside a process.

6.2 Creating Threads — Two Ways

Creating Threads

// WAY 1: Extend Thread class


class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](getName() + " : " + i);
}
}
}
MyThread t1 = new MyThread();
[Link](); // starts new thread — DO NOT call run() directly!

// WAY 2: Implement Runnable (preferred)


class MyRunnable implements Runnable {
@Override
public void run() {
[Link]("Running: " + [Link]().getName());
}
}
Thread t2 = new Thread(new MyRunnable(), "Worker-1");
[Link]();

// WAY 3: Lambda (Java 8+)


Thread t3 = new Thread(() -> [Link]("Lambda thread!"));
[Link]();

Extend Thread Implement Runnable

Inheritance Class is tied — cannot Free to extend another class


extend another class

Flexibility Low High (preferred)

Java Complete Revision Guide Page 26


Extend Thread Implement Runnable

Resource sharing Each thread is a separate Same Runnable can share between threads
object

Use when Simple, standalone Complex apps; best practice


threads

6.3 Thread Methods & Priority

Thread Methods

Thread t = new Thread(task);


[Link](); // begins thread execution
[Link](1000); // pauses current thread 1 second (throws InterruptedException)
[Link](); // current thread waits for t to finish
[Link]("Worker"); // give thread a name
[Link](); // get name
[Link](); // true if thread is running

// Priority (1=MIN, 5=NORM, 10=MAX)


[Link](Thread.MAX_PRIORITY); // 10
[Link](Thread.MIN_PRIORITY); // 1
[Link]();

CAUTION
Thread priority is a HINT to the OS scheduler — not a guarantee of execution order.

6.4 Race Condition & Synchronization

A race condition occurs when multiple threads access shared data simultaneously and the outcome
depends on thread scheduling order. Fix with synchronized.

Java Complete Revision Guide Page 27


Synchronization

// PROBLEM — race condition


class Counter {
int count = 0;
void increment() { count++; } // NOT thread-safe
}

// SOLUTION — synchronized method


class SafeCounter {
int count = 0;
synchronized void increment() { count++; } // only one thread at a time
}

// SOLUTION — synchronized block (finer control)


void increment() {
synchronized(this) {
count++;
}
}

6.5 Thread Lifecycle States

State Description

New Thread created but start() not called

Runnable start() called; waiting for CPU time

Running Thread is executing

Blocked/Waiting Waiting for a monitor lock or another thread

Timed Waiting sleep() or wait(timeout) called

Terminated run() completed or exception thrown

Java Complete Revision Guide Page 28


CHAPTER 07

Collections & Stream API


ArrayList · Set · Map · Comparator · forEach · Stream · Map-Filter-Reduce

7.1 Collections Framework Overview

The Java Collections Framework provides ready-made data structures. Root interface: Collection
(except Map).

Interface Implementation Ordere Sorted Duplicates Null


d

List ArrayList, Yes No Yes Yes


LinkedList

Set HashSet No No No 1 null

Set LinkedHashSet Insertio No No 1 null


n order

Set TreeSet No Yes (n No No


atural)

Map HashMap No No Keys unique 1 null key

Map LinkedHashMap Insertio No Keys unique 1 null key


n order

Map TreeMap No Yes Keys unique No


(keys)

Queue PriorityQueue Priority Natural Yes No

7.2 ArrayList

Java Complete Revision Guide Page 29


ArrayList

import [Link].*;
ArrayList<String> list = new ArrayList<>();

[Link]("Java"); // add at end


[Link](0, "Python"); // add at index
[Link](0); // "Python"
[Link](0, "Kotlin"); // replace
[Link]("Java"); // by value
[Link](0); // by index
[Link](); // count
[Link]("Kotlin"); // true/false
[Link]("Kotlin"); // index
[Link](); // true/false
[Link](); // remove all
[Link](list); // sort alphabetically
[Link](list); // reverse

7.3 Set & Map

Set & Map

// HashSet — no duplicates, no order


Set<Integer> set = new HashSet<>();
[Link](3); [Link](1); [Link](4); [Link](1);
[Link](set); // [1, 3, 4] — no duplicate 1

// HashMap — key-value pairs


Map<String, Integer> map = new HashMap<>();
[Link]("Alice", 95);
[Link]("Bob", 87);
[Link]("Charlie", 92);

[Link]("Alice"); // 95
[Link]("Bob"); // true
[Link](92); // true
[Link]("Bob");
[Link](); // 2

// Iterating Map
for ([Link]<String, Integer> e : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
}
[Link]((k, v) -> [Link](k + ": " + v));

7.4 Comparator vs Comparable

Java Complete Revision Guide Page 30


Comparable Comparator

Package [Link] [Link]

Method int compareTo(T o) int compare(T o1, T o2)

Modifies class Yes (implements interface) No (separate class/lambda)

Sort orders One natural order Multiple custom orders

Used with [Link](list) [Link](list, comp)

Comparator vs Comparable

// Comparable — inside the class


class Student implements Comparable<Student> {
String name; int marks;
@Override
public int compareTo(Student o) { return [Link] - [Link]; }
}
[Link](students); // sorts by marks

// Comparator — external / lambda


Comparator<Student> byName = (a, b) -> [Link]([Link]);
Comparator<Student> byMarks = [Link](s -> [Link]);
Comparator<Student> reversed = [Link]();

[Link](byName); // sort by name


[Link](reversed); // sort marks descending

7.5 Stream API (Java 8+)

Streams allow functional-style operations on collections — filter, map, reduce, sort — in a declarative
way. Streams are lazy and do not modify the source.

Java Complete Revision Guide Page 31


Stream API

import [Link].*;

List<Integer> nums = [Link](1,2,3,4,5,6,7,8,9,10);

// filter — keep elements matching predicate


List<Integer> evens = [Link]()
.filter(n -> n % 2 == 0)
.collect([Link]()); // [2,4,6,8,10]

// map — transform each element


List<Integer> squares = [Link]()
.map(n -> n * n)
.collect([Link]());

// reduce — combine all into one


int sum = [Link]()
.reduce(0, Integer::sum); // 55

// sorted + distinct + limit + skip


[Link]().sorted().distinct().limit(5).forEach([Link]::println);

// count, min, max


long count = [Link]().filter(n -> n > 5).count(); // 5
Optional<Integer> max = [Link]().max(Integer::compareTo);

// Collectors
String joined = [Link]().collect([Link](", "));
Map<Boolean,List<Integer>> partitioned =
[Link]().collect([Link](n -> n%2==0));

CAUTION
Streams are one-time use. A stream cannot be reused after a terminal operation.

Java Complete Revision Guide Page 32


CHAPTER 08

Wrapper Classes
Autoboxing · Unboxing · Caching · Utility Methods · parseInt & more

8.1 What Are Wrapper Classes?

Primitive types (int, double, char, etc.) are NOT objects — they cannot be used in Collections, Generics,
or as method arguments expecting Object. Wrapper Classes wrap each primitive into an Object.

Primitive Wrapper Size Default


Class

byte Byte 8-bit 0

short Short 16-bit 0

int Integer 32-bit 0

long Long 64-bit 0L

float Float 32-bit 0.0f

double Double 64-bit 0.0

char Character 16-bit \u0000

boolean Boolean — false

INFO
All Wrapper classes are in [Link] package — imported automatically.

IMPORTANT
All Wrapper classes are IMMUTABLE and FINAL — they cannot be subclassed or modified.

8.2 Creating Wrapper Objects

Java Complete Revision Guide Page 33


Creating Wrapper Objects

// OLD WAY — constructor (deprecated in Java 9+)


Integer i1 = new Integer(42); // deprecated
Double d1 = new Double(3.14); // deprecated

// RECOMMENDED — valueOf() (uses Integer Cache)


Integer i2 = [Link](42);
Double d2 = [Link](3.14);

// String to Wrapper
Integer i3 = [Link]("100");
Double d3 = [Link]("3.14");

// Autoboxing — compiler does it automatically (Java 5+)


Integer i4 = 42; // compiler calls [Link](42)
Double d4 = 3.14;

8.3 Autoboxing & Unboxing

Autoboxing: Automatic conversion from primitive to Wrapper object (done by compiler).

Unboxing: Automatic conversion from Wrapper object back to primitive.

Autoboxing & Unboxing

// AUTOBOXING — primitive to Wrapper


int primitiveInt = 5;
Integer wrapperInt = primitiveInt; // autoboxing
// compiler rewrites this as:
// Integer wrapperInt = [Link](primitiveInt);

// UNBOXING — Wrapper to primitive


Integer w = [Link](10);
int p = w; // unboxing
// compiler rewrites this as:
// int p = [Link]();

// Autoboxing in Collections — VERY common


List<Integer> list = new ArrayList<>();
[Link](10); // int 10 autoboxed to Integer
[Link](20);
int total = [Link](0) + [Link](1); // unboxed to int for arithmetic

// Autoboxing in expressions
Integer a = 5;
Integer b = 10;
int sum = a + b; // both unboxed, added, result is int

CAUTION
NullPointerException trap: Integer x = null; int y = x; → NullPointerException at unboxing!

Java Complete Revision Guide Page 34


8.4 Integer Caching (Important for Interviews!)

Java caches Integer objects for values -128 to 127. Integers in this range created via autoboxing or
valueOf() return the SAME cached object.

Integer Cache

Integer a = 127;
Integer b = 127;
[Link](a == b); // TRUE (same cached object)

Integer c = 128;
Integer d = 128;
[Link](c == d); // FALSE (new objects, beyond cache)
[Link]([Link](d)); // TRUE (value comparison)

// Why this happens:


[Link](127) === [Link](127) // same cached instance
[Link](128) !== [Link](128) // different new instances

// RULE: ALWAYS use .equals() for Wrapper comparisons, never ==


[Link](d) // always correct

TIP
Cache range -128 to 127 is guaranteed by JLS. JVM can extend it via JVM flags.

8.5 Converting Between Types — Parsing Methods

Parsing & Converting

// String → Primitive
int i = [Link]("42");
double d = [Link]("3.14");
long l = [Link]("9876543210");
float f = [Link]("1.5");
boolean b = [Link]("true"); // case-insensitive

// Primitive → String
String s1 = [Link](42);
String s2 = [Link](42);
String s3 = "" + 42; // concatenation trick (avoid)

// Wrapper → Primitive (unboxing methods)


Integer w = 100;
int iv = [Link]();
long lv = [Link]();
double dv = [Link]();

// Primitive → Wrapper (boxing methods)


Integer wrapped = [Link](42);

Java Complete Revision Guide Page 35


8.6 Utility Methods of Wrapper Classes

Integer Utility Methods

Integer Methods

Integer.MAX_VALUE // 2147483647
Integer.MIN_VALUE // -2147483648
[Link] // 32 (bits)
[Link] // 4 (bytes)

[Link](10) // "1010"
[Link](8) // "10"
[Link](255) // "ff"

[Link](7) // 3 (number of 1-bits)


[Link](1) // reverses bit pattern
[Link](10) // 8
[Link](1) // 31
[Link](8) // 3

[Link](5, 10) // negative (5 < 10)


[Link](5, 10) // 10
[Link](5, 10) // 5
[Link](5, 10) // 15

[Link]("1010", 2) // 10 — parse binary string


[Link]("FF", 16) // 255 — parse hex string

Character Utility Methods

Character Methods

char c = 'A';

[Link](c) // false
[Link](c) // true
[Link](c)// true
[Link](c) // true
[Link](c) // false
[Link](c) // false

[Link]('a') // 'A'
[Link]('A') // 'a'

[Link]('5') // 5
[Link]('9', 10) // 9

Double & Math Utilities

Java Complete Revision Guide Page 36


Double & Math

Double.MAX_VALUE // 1.7976931348623157E308
Double.MIN_VALUE // 4.9E-324 (smallest positive)
[Link](0.0 / 0.0) // true
[Link](1.0/0) // true

// Math class (all static)


[Link](-5) // 5
[Link](2, 10) // 1024.0
[Link](144) // 12.0
[Link](4.1) // 5.0
[Link](4.9) // 4.0
[Link](4.5) // 5
[Link](5, 10) // 10
[Link](5, 10) // 5
[Link](Math.E) // 1.0
Math.log10(1000) // 3.0
[Link] // 3.141592653589793
[Link]() // [0.0, 1.0)

8.7 Wrapper Classes in Collections & Generics

Wrapper in Collections

// Collections require Object types — primitives not allowed


List<int> list1 = new ArrayList<>(); // COMPILE ERROR
List<Integer> list2 = new ArrayList<>(); // OK

// Common pattern — count frequency with Map


String text = "hello world";
Map<Character, Integer> freq = new HashMap<>();
for (char c : [Link]()) {
[Link](c, [Link](c, 0) + 1); // autoboxing
}

// Generic method using wrapper


public <T extends Number> double sum(List<T> list) {
return [Link]()
.mapToDouble(Number::doubleValue)
.sum();
}

// Sorting integers correctly


List<Integer> nums = [Link](3, 1, 4, 1, 5, 9, 2, 6);
[Link](nums); // natural order
[Link](Integer::compare); // same result
[Link]([Link]()); // descending

8.8 Common Pitfalls with Wrapper Classes

Java Complete Revision Guide Page 37


Pitfall Problem Code Fix

NullPointerException Integer x = null; int y = x; Always null-check before unboxing

== vs equals Integer a=128; Integer Use [Link](b) always


b=128; a==b

Performance Autoboxing in tight loops Use primitives in loops

Slow arithmetic Integer sum=0; sum+=i; (in Use int sum, autobox only at end
loop)

Boolean trap Boolean flag=null; if(flag){} Initialize to true/false, not null

Pitfalls

// PITFALL 1: NullPointerException on unboxing


Integer x = null;
int y = x; // NullPointerException!
int y = (x != null) ? x : 0; // safe

// PITFALL 2: Performance — avoid in hot loops


Long sum = 0L;
for (long i = 0; i < 1_000_000; i++) {
sum += i; // creates ~1M Long objects!
}
// FIX:
long sum2 = 0L; // primitive — fast
for (long i = 0; i < 1_000_000; i++) sum2 += i;

Java Complete Revision Guide Page 38


CHAPTER 09

Interview & Practice Questions


80+ Questions · Topic-wise · With Hints · Logic Building

9.1 Java Fundamentals — Questions

Practice Questions

Q Write a program to check if a number is prime.


1

Hint: Loop from 2 to sqrt(n). Use [Link]().

Q Swap two numbers without a third variable.


2

Hint: Use a=a+b; b=a-b; a=a-b; or XOR method.

Q Find the factorial of a number using recursion.


3

Hint: Base: fact(0)=1. Recursive: n*fact(n-1).

Q Print Fibonacci series up to N terms.


4

Hint: Each term = sum of previous two.

Q Reverse an integer without converting to String.


5

Hint: Use % 10 to extract digits, rebuild.

Q Check if a number is palindrome.


6

Hint: Reverse the number; compare with original.

Q Count digits, vowels, consonants in a String.


7

Hint: Loop + [Link](), isLetter().

Q Find sum of digits of a number.


8

Hint: n%10 gives last digit; n/10 removes it. Loop.

Interview Questions

Java Complete Revision Guide Page 39


Q What is the difference between == and .equals()?
1

Hint: == compares references. .equals() compares content (when overridden).

Q What is the difference between break and continue?


2

Hint: break exits the loop entirely. continue skips the current iteration.

Q Why is Java platform-independent?


3

Hint: Compiler produces platform-neutral bytecode. JVM interprets it on any OS.

Q What is the difference between JDK, JRE, and JVM?


4

Hint: JDK=dev kit, JRE=runtime, JVM=bytecode executor. JDK⊃JRE⊃JVM.

Q Can we have multiple main methods in Java?


5

Hint: Yes (overloading) — but only public static void main(String[]) is the entry point.

9.2 OOP — Questions

Practice Questions

Q Create a class Shape with area(). Extend to Circle, Rectangle, Triangle.


1

Hint: Abstract class + override in each subclass.

Q Implement a Stack class with push, pop, peek using arrays.


2

Hint: Track top index. push increments, pop decrements.

Q Design a BankAccount class with deposit, withdraw, and balance checking.


3

Hint: Use encapsulation — private balance with validated setters.

Q Create a Student class implementing Comparable to sort by GPA.


4

Hint: compareTo returns [Link] - [Link] (or [Link]).

Q Demonstrate method overloading with an add() method for int, double, String.
5

Java Complete Revision Guide Page 40


Hint: Same name, different parameter types — resolved at compile time.

Q Show runtime polymorphism using an Animal hierarchy.


6

Hint: Parent reference, child objects. Call overridden method.

Interview Questions

Q What are the 4 pillars of OOP? Explain each briefly.


1

Hint: Encapsulation, Inheritance, Polymorphism, Abstraction — memorize with examples.

Q Why does Java not support multiple inheritance with classes?


2

Hint: Diamond problem. Solved via interfaces with default methods.

Q Can a constructor be private? What is the use?


3

Hint: Yes — used in Singleton pattern to prevent external instantiation.

Q What is the difference between abstract class and interface?


4

Hint: Abstract: partial implementation, can have state. Interface: contract, no state.

Q What is constructor chaining?


5

Hint: Calling one constructor from another using this() or super().

Q Can we override static methods?


6

Hint: No — static methods are hidden, not overridden. No dynamic dispatch.

Q What is the use of the super keyword?


7

Hint: Access parent class constructor, field, or method from child class.

9.3 Strings & Arrays — Questions

Practice Questions

Q Check if a String is a palindrome.


1

Java Complete Revision Guide Page 41


Hint: Compare s with [Link]() or use two pointers.

Q Count occurrences of each character in a String.


2

Hint: Use HashMap or int[256].

Q Find the longest substring without repeating characters.


3

Hint: Sliding window with a HashSet.

Q Find two numbers in an array that sum to a target.


4

Hint: Use HashMap: store complement, check on each iteration.

Q Sort an array of 0s, 1s, and 2s in one pass.


5

Hint: Dutch National Flag — 3 pointers: low, mid, high.

Q Find the second largest element in an array.


6

Hint: Track largest and second largest in one pass.

Q Remove duplicates from an unsorted array.


7

Hint: Use LinkedHashSet to preserve order.

Q Rotate an array by k positions.


8

Hint: Reverse entire, reverse first k, reverse remaining.

Q Check if two Strings are anagrams.


9

Hint: Sort both and compare, or count char frequency.

Q Find all substrings of a String.


10

Hint: Nested loops: outer = start, inner = end position.

9.4 Wrapper Classes — Interview Questions

Must-Know Wrapper Questions

Java Complete Revision Guide Page 42


Q What is the output of: Integer a=127; Integer b=127; [Link](a==b)?
1

Hint: TRUE — values in -128..127 are cached. Same object returned by valueOf.

Q What is the output of: Integer a=128; Integer b=128; [Link](a==b)?


2

Hint: FALSE — outside cache range. Two different objects. Use .equals() instead.

Q What is Autoboxing? Where is it used?


3

Hint: Automatic primitive-to-Wrapper conversion. Used in Collections, generics, assignments.

Q Can NullPointerException occur with Wrapper classes?


4

Hint: Yes! Integer x = null; int y = x; throws NPE during unboxing.

Q Why are Wrapper classes immutable?


5

Hint: Safety, caching (Integer pool), use as HashMap keys — mutable keys break hashing.

Q Difference between parseInt() and valueOf().


6

Hint: parseInt returns primitive int. valueOf returns Integer object.

Q What is [Link]("1010", 2)?


7

Hint: Parses binary string '1010' = 10 in decimal. Second arg is the radix.

Q How to convert int to binary/octal/hex String?


8

Hint: [Link](n), toOctalString(n), toHexString(n).

Q What is the MAX and MIN value of Integer?


9

Hint: Integer.MAX_VALUE = 2^31-1 = 2147483647. MIN_VALUE = -2^31.

Q Why should we avoid using == with Wrapper classes?


10

Hint: == compares object references, not values. Only cached values (-128..127) give true for ==.

9.5 Exception Handling — Questions

Java Complete Revision Guide Page 43


Q Difference between checked and unchecked exceptions?
1

Hint: Checked: verified at compile time (must handle). Unchecked: runtime — extend RuntimeException.

Q What is the difference between throw and throws?


2

Hint: throw: action (throws one exception). throws: declaration (can list multiple).

Q Can finally block be skipped?


3

Hint: Only if JVM exits ([Link]()) or JVM crashes.

Q What is try-with-resources?
4

Hint: Auto-closes AutoCloseable resources. Cleaner than finally for I/O streams.

Q Can we have try without catch?


5

Hint: Yes — try-finally is valid. Or try-with-resources.

Q What is exception chaining?


6

Hint: Wrapping one exception in another: new RuntimeException('msg', cause).

9.6 Multithreading — Questions

Q What is the difference between Thread and Runnable?


1

Hint: Runnable is preferred — class can extend another. Thread ties inheritance.

Q What is a race condition? How to prevent it?


2

Hint: Multiple threads access shared data unsafely. Fix with synchronized or Lock.

Q What is deadlock?
3

Hint: Two threads each hold a lock the other needs — circular wait. Prevent by lock ordering.

Q Difference between sleep() and wait()?


4

Hint: sleep: pauses thread for time, holds lock. wait: pauses and releases lock, needs notify.

Java Complete Revision Guide Page 44


Q What is the volatile keyword?
5

Hint: Makes variable reads/writes go to main memory — visibility guarantee across threads.

9.7 Collections — Questions

Q Difference between ArrayList and LinkedList?


1

Hint: ArrayList: fast random access O(1). LinkedList: fast insert/delete O(1). Both O(n) search.

Q How does HashMap work internally?


2

Hint: Array of buckets. hashCode() finds bucket. Linked list/TreeNode handles collisions (chaining).

Q Difference between HashMap and TreeMap?


3

Hint: HashMap: O(1) get/put, no order. TreeMap: O(log n), sorted by keys.

Q What happens if we put a duplicate key in HashMap?


4

Hint: Value is replaced. Key set remains unchanged. put() returns the old value.

Q Difference between Iterator and ListIterator?


5

Hint: Iterator: forward only, any Collection. ListIterator: bidirectional, List only.

Q What is ConcurrentModificationException?
6

Hint: Modifying a collection while iterating it. Use [Link]() or CopyOnWriteArrayList.

9.8 Logic Building Questions

Think Before You Code

Q Given an array, find the subarray with the maximum sum.


1

Hint: Kadane's Algorithm — track current_max and global_max in one pass.

Q Check if brackets in a String are balanced.


2

Java Complete Revision Guide Page 45


Hint: Stack — push open brackets, pop on close, check match.

Q Implement a simple LRU Cache.


3

Hint: LinkedHashMap with access-order=true. Override removeEldestEntry.

Q Find if a linked list has a cycle.


4

Hint: Floyd's cycle detection — slow pointer 1 step, fast 2 steps. If they meet, cycle exists.

Q Count number of islands in a grid of 0s and 1s.


5

Hint: DFS from each unvisited '1'. Mark visited. Increment island count.

Q Generate all permutations of a String.


6

Hint: Recursive backtracking — fix one char, permute rest.

Q Find the Nth Fibonacci number in O(log N).


7

Hint: Matrix exponentiation or fast doubling formula.

Q Design a system to find the top K frequent elements.


8

Hint: HashMap for frequency + Min-Heap of size K or bucket sort by frequency.

Java Complete Revision Guide Page 46


CHAPTER 10

Quick Reference Cheat Sheet


String Methods · Collections · Stream · Keywords · Complexity

10.1 String Methods Cheat Sheet

Method Returns Example

length() int "Hello".length() → 5

charAt(i) char "Hello".charAt(1) → e

indexOf(s) int "Hello".indexOf("l") → 2

lastIndexOf(s) int "Hello".lastIndexOf("l") → 3

substring(s,e) String "Hello".substring(1,3) → el

toUpperCase() String "hello".toUpperCase() → HELLO

toLowerCase() String "HELLO".toLowerCase() → hello

trim() String " hi ".trim() → hi

replace(a,b) String "cat".replace("a","o") → cot

contains(s) boolean "Hello".contains("ell") → true

startsWith(s) boolean "Hello".startsWith("He") → true

endsWith(s) boolean "Hello".endsWith("lo") → true

split(regex) String[] "a,b,c".split(",") → [a,b,c]

equals(s) boolean "hi".equals("hi") → true

equalsIgnoreCase(s) boolean "Hi".equalsIgnoreCase("hi") → true

isEmpty() boolean " ".isEmpty() → false (has space)

isBlank() boolean " ".isBlank() → true (Java 11+)

toCharArray() char[] "abc".toCharArray() → [a,b,c]

valueOf(x) String [Link](42) → "42"

format(fmt,...) String [Link]("%d %.2f",5,3.14)

10.2 Collections Complexity

Java Complete Revision Guide Page 47


Structure Add Remove Get/Search Notes

ArrayList O(1) amort. O(n) O(1) by Dynamic array; slow middle insert
index

LinkedList O(1) O(1) with O(n) Doubly linked; no random access


ref

HashSet O(1) avg O(1) avg O(1) avg Hash table; no order

TreeSet O(log n) O(log n) O(log n) Red-Black tree; sorted

HashMap O(1) avg O(1) avg O(1) avg Key-value; no order

TreeMap O(log n) O(log n) O(log n) Sorted by key

PriorityQueue O(log n) O(log n) O(1) peek Min-heap by default

10.3 Java Keywords Quick Reference

Keyword Purpose

this Reference to current class instance

super Reference to parent class constructor/method/field

static Class-level member — shared across all objects

final Constant variable / prevent override / prevent inheritance

abstract Incomplete class or method — must be extended/implemented

synchronized Thread-safe block or method — one thread at a time

volatile Ensures variable read/write from/to main memory

transient Exclude field from serialization

instanceof Check if object is instance of a class/interface

new Allocate object in heap memory

null Default value for reference types — no object referenced

void Method has no return value

10.4 Stream API Cheat Sheet

Operation Type Method Example

filter Intermediate filter(Predicate) [Link](x -> x>0)

map Intermediate map(Function) [Link](x -> x*2)

Java Complete Revision Guide Page 48


Operation Type Method Example

sorted Intermediate sorted() [Link]()

distinct Intermediate distinct() [Link]()

limit Intermediate limit(n) [Link](5)

skip Intermediate skip(n) [Link](2)

peek Intermediate peek(Consumer) [Link]([Link]::println)

forEach Terminal forEach(Consumer) [Link]([Link]::println)

collect Terminal collect(Collector) [Link](toList())

reduce Terminal reduce(identity,BinaryO [Link](0, Integer::sum)


p)

count Terminal count() [Link]()

min/max Terminal min/max(Comparator) [Link](Integer::compare)

anyMatch Terminal anyMatch(Predicate) [Link](x->x>5)

allMatch Terminal allMatch(Predicate) [Link](x->x>0)

findFirst Terminal findFirst() [Link]()

10.5 Exception Hierarchy

Exception Hierarchy

[Link]
■■■ [Link] (unchecked — don't handle)
■ ■■■ OutOfMemoryError
■ ■■■ StackOverflowError
■ ■■■ VirtualMachineError
■■■ [Link]
■■■ RuntimeException (unchecked)
■ ■■■ NullPointerException
■ ■■■ ArrayIndexOutOfBoundsException
■ ■■■ ClassCastException
■ ■■■ ArithmeticException
■ ■■■ NumberFormatException
■ ■■■ IllegalArgumentException
■ ■■■ IllegalStateException
■■■ Checked Exceptions (must handle)
■■■ IOException
■ ■■■ FileNotFoundException
■ ■■■ EOFException
■■■ SQLException
■■■ ClassNotFoundException
■■■ InterruptedException

Java Complete Revision Guide Page 49


10.6 OOP Concepts Mind Map Summary

Concept One-Line Definition Key Rule

Encapsulation Wrapping data + methods, hiding private fields + public getters/setters


internals

Inheritance Child acquires parent properties extends; single class, multi interface

Polymorphism One interface, multiple forms Overloading=compile; Overriding=runtime

Abstraction Hide implementation, show only abstract class or interface


interface

Association One class uses another HAS-A relationship

Composition Strong HAS-A — child cannot Parts are destroyed with whole
exist without parent

Aggregation Weak HAS-A — child can exist Department has Students


independently

Coupling How dependent classes are on Low coupling = good design


each other

Cohesion How focused a class is on one High cohesion = good design


responsibility

10.7 Naming Conventions

Element Convention Example

Class / Interface UpperCamelCase StudentRecord, Runnable


(PascalCase)

Method / Variable lowerCamelCase getStudentName(), totalAmount

Constant (static final) UPPER_SNAKE_CASE MAX_SIZE, PI

Package all lowercase, dots as [Link]


separator

Generic Type Single uppercase letter T, E, K, V, N

Boolean variable Start with is/has/can isActive, hasChildren

Java Complete Revision Guide Page 50

You might also like