1
JDK, JRE and JVM
★★★★★
↑ Index
Java
Java source code is compiled by javac into bytecode (.class). The JVM runs that bytecode on any operating system, which makes Java platform independent.

JDK contains the JRE, the JRE contains the JVM
Structure of a Java program · Java
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
// javac Hello.java → Hello.class
// java Hello → runs on the JVM
Q & A
- Why is main public static void?
public: the JVM must call it from outside. static: it runs without creating an object. void: it returns nothing to the JVM.
- Is Java fully object oriented?
Not 100%, because it has primitive types (int, char, ...) and static members.
2
Java Data Types and Wrapper Classes
↑ Index
Java
| Primitive | Size | Wrapper |
|---|
| byte | 1 byte | Byte |
| short | 2 bytes | Short |
| int | 4 bytes | Integer |
| long | 8 bytes | Long |
| float | 4 bytes | Float |
| double | 8 bytes | Double |
| char | 2 bytes (Unicode) | Character |
| boolean | JVM specific | Boolean |
Autoboxing converts a primitive to its wrapper automatically (int → Integer); unboxing is the reverse. Collections can only store objects, so they use wrappers.
Java
Integer a = 5; // autoboxing
int b = a; // unboxing
int n = Integer.parseInt("42");
String s = String.valueOf(99);
Integer x = 127, y = 127;
System.out.println(x == y); // true (cached -128..127)
Integer p = 128, q = 128;
System.out.println(p == q); // false (different objects)
System.out.println(p.equals(q)); // true
3
String, StringBuilder and StringBuffer
★★★★★
↑ Index
Java
| String | StringBuilder | StringBuffer |
|---|
| Immutable | Mutable | Mutable |
| Thread-safe (because immutable) | Not thread-safe | Thread-safe (synchronized) |
| Slow for many changes | Fastest | Slower than StringBuilder |
Java
String s1 = "hello"; // string pool
String s2 = "hello"; // same pool object
String s3 = new String("hello"); // new heap object
System.out.println(s1 == s2); // true (same reference)
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s3)); // true (same content)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i);
System.out.println(sb.reverse()); // 43210
Q & A
- == vs equals()?
== compares references (same object?). equals() compares content. Always use equals() for strings.
- Why is String immutable?
For security (class names, URLs, passwords), string pool sharing, thread safety and caching the hashCode.
Java
Java
abstract class Animal {
protected String name;
Animal(String name) { this.name = name; }
abstract void sound(); // must be overridden
void sleep() { System.out.println(name + " sleeps"); }
}
interface Pet { void play(); }
class Dog extends Animal implements Pet {
Dog(String name) { super(name); } // call parent constructor
@Override void sound() { System.out.println("Woof"); }
public void play() { System.out.println(name + " plays"); }
}
Animal a = new Dog("Tommy"); // upcasting → run-time polymorphism
a.sound(); // Woof
extends — one class only; implements — many interfaces.super — parent constructor or method; this — current object.final class cannot be extended, final method cannot be overridden, final variable cannot be reassigned.- All non-static, non-final, non-private methods are virtual by default in Java.
5
Exception Handling in Java
★★★★★
↑ Index
Java
| Checked exception | Unchecked exception |
|---|
| Checked at compile time | Happens at run time |
| Must be caught or declared with throws | Not forced |
| IOException, SQLException, FileNotFoundException | NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException |
Hierarchy: Throwable → Error (OutOfMemoryError, StackOverflowError — do not catch) and Exception → RuntimeException (unchecked).
Java
try {
int[] arr = new int[3];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index: " + e.getMessage());
} finally {
System.out.println("finally always runs");
}
// try-with-resources closes the reader automatically
try (BufferedReader br = new BufferedReader(new FileReader("a.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
class InsufficientBalanceException extends Exception { // custom checked exception
InsufficientBalanceException(String msg) { super(msg); }
}
Q & A
- throw vs throws?
throw actually throws one exception object inside a method. throws in the method signature declares which checked exceptions the method may throw.
- final vs finally vs finalize?
final: keyword for constants / no override / no inheritance. finally: block that always runs after try-catch. finalize(): old GC hook, deprecated.
6
Java Collections Framework
★★★★★
↑ Index
Java

List, Set, Queue and Map with their common implementations
| Class | Order | Duplicates | Lookup |
|---|
| ArrayList | Insertion | Yes | get(i) O(1) |
| LinkedList | Insertion | Yes | get(i) O(n) |
| HashSet | None | No | O(1) |
| TreeSet | Sorted | No | O(log n) |
| HashMap | None | Keys unique | O(1) |
| TreeMap | Sorted by key | Keys unique | O(log n) |
Java
List<Integer> list = new ArrayList<>(List.of(5, 2, 8));
Collections.sort(list); // [2, 5, 8]
Map<String, Integer> freq = new HashMap<>();
for (String w : "a b a c a".split(" "))
freq.put(w, freq.getOrDefault(w, 0) + 1);
System.out.println(freq); // {a=3, b=1, c=1}
Set<String> set = new TreeSet<>(List.of("b", "a", "b")); // [a, b]
Q & A
- HashMap vs Hashtable?
HashMap is not synchronized, allows one null key, faster. Hashtable is synchronized (legacy) and allows no null. For threads use ConcurrentHashMap.
- How does HashMap work?
hashCode() picks a bucket; entries in the same bucket form a linked list (a red-black tree after 8 entries); equals() finds the exact key.
7
Multithreading in Java
↑ Index
Java
A thread is a lightweight unit of execution inside a process. Create one by extending Thread or implementing Runnable (preferred).

New → Runnable → Running → Terminated
Java
class Counter {
private int count = 0;
public synchronized void increment() { count++; } // one thread at a time
public int get() { return count; }
}
Counter c = new Counter();
Runnable task = () -> { for (int i = 0; i < 1000; i++) c.increment(); };
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start();
t1.join(); t2.join(); // wait for both
System.out.println(c.get()); // 2000
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> System.out.println("from the pool"));
pool.shutdown();
start() creates a new thread and calls run(); calling run() directly just runs it on the current thread.
8
static and final in Java
↑ Index
Java
- static variable — one copy for the whole class.
- static method — called with the class name; cannot use
this or instance members. - static block — runs once when the class loads.
- final — constant variable, method that cannot be overridden, class that cannot be extended (e.g. String).
Java
class Config {
static final double PI = 3.1416; // constant
static int instances;
static { System.out.println("class loaded"); }
Config() { instances++; }
}
9
Java 8 Features: Lambda and Streams
↑ Index
Java
Java 8 added lambda expressions, functional interfaces (one abstract method), the Stream API, Optional, default methods in interfaces and the new Date/Time API.
Java
List<String> names = List.of("Rahim", "Karim", "Sumi", "Ria");
List<String> result = names.stream()
.filter(n -> n.length() > 3)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList()); // [KARIM, RAHIM, SUMI]
int sum = IntStream.rangeClosed(1, 100).sum(); // 5050
Optional<String> first = names.stream().filter(n -> n.startsWith("Z")).findFirst();
System.out.println(first.orElse("none"));