Java Basics
Hello World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Data Types
// Primitives
byte b = 127; // 1 byte
short s = 32767; // 2 bytes
int i = 2147483647; // 4 bytes
long l = 9223372036854775807L; // 8 bytes
float f = 3.14f; // 4 bytes
double d = 3.14159; // 8 bytes
char c = 'A'; // 2 bytes
boolean bool = true; // 1 bit
// Reference types
String str = "Hello";
int[] arr = {1, 2, 3};
Variables
// Declaration
int x;
int y = 10;
final int CONST = 100; // Constant
// Multiple declarations
int a = 1, b = 2, c = 3;
// Type inference (Java 10+)
var list = new ArrayList<String>();
var name = "John";
Operators
// Arithmetic
+ - * / % ++ --
// Comparison
== != < > <= >=
// Logical
&& || !
// Assignment
= += -= *= /= %=
// Ternary
result = (condition) ? value1 : value2;
// instanceof
if (obj instanceof String s) { }
Control Flow
// If-else
if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}
// Switch (expression - Java 14+)
String result = switch (day) {
case "MON", "TUE" -> "Weekday";
case "SAT", "SUN" -> "Weekend";
default -> "Unknown";
};
Loops
// For loop
for (int i = 0; i < 10; i++) { }
// Enhanced for loop
for (String item : list) { }
// While loop
while (condition) { }
// Do-while loop
do {
// code
} while (condition);
// Control
break; // Exit loop
continue; // Skip iteration
Arrays
// Declaration
int[] arr = new int[5];
int[] arr = {1, 2, 3, 4, 5};
// 2D Array
int[][] matrix = new int[3][4];
int[][] matrix = {{1,2}, {3,4}};
// Operations
arr.length // Length
Arrays.sort(arr); // Sort
Arrays.fill(arr, 0); // Fill
Arrays.copyOf(arr, 10); // Copy
Arrays.toString(arr); // Print
Strings
String s = "Hello";
// Common Methods
s.length() // 5
s.charAt(0) // 'H'
s.substring(1, 4) // "ell"
s.toUpperCase() // "HELLO"
s.toLowerCase() // "hello"
s.trim() // Remove whitespace
s.split(",") // Split to array
s.contains("ell") // true
s.startsWith("He") // true
s.replace("l", "L") // "HeLLo"
s.equals("Hello") // true
s.equalsIgnoreCase() // Case-insensitive
// StringBuilder (mutable)
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" World");
sb.toString(); // "Hello World"
Object-Oriented Programming
Class & Object
public class Person {
// Fields
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter/Setter
public String getName() { return name; }
public void setName(String name) {
this.name = name;
}
}
// Create object
Person p = new Person("John", 25);
Inheritance
class Animal {
protected String name;
public void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
public Dog(String name) {
super.name = name; // Access parent
}
@Override
public void eat() {
super.eat(); // Call parent method
System.out.println("Dog eating");
}
public void bark() {
System.out.println("Woof!");
}
}
Abstract Class
abstract class Shape {
protected String color;
// Abstract method (no body)
public abstract double area();
// Concrete method
public void display() {
System.out.println("Color: " + color);
}
}
class Circle extends Shape {
private double radius;
@Override
public double area() {
return Math.PI * radius * radius;
}
}
Interface
interface Drawable {
// Constants (public static final)
int MAX_SIZE = 100;
// Abstract method
void draw();
// Default method (Java 8+)
default void print() {
System.out.println("Printing...");
}
// Static method
static void info() {
System.out.println("Drawable interface");
}
}
class Rectangle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing rectangle");
}
}
Access Modifiers
public // Everywhere
protected // Same package + subclasses
// default // Same package only
private // Same class only
// Non-access modifiers
static // Class level
final // Cannot change/override/extend
abstract // No implementation
synchronized // Thread safe
volatile // Memory visibility
transient // Skip serialization
Static Members
class Counter {
private static int count = 0;
private int id;
// Static block
static {
System.out.println("Class loaded");
}
public Counter() {
count++;
id = count;
}
// Static method
public static int getCount() {
return count;
}
}
// Access without object
Counter.getCount();
Records (Java 16+)
// Immutable data class
public record Person(String name, int age) {
// Compact constructor
public Person {
if (age < 0)
throw new IllegalArgumentException();
}
}
// Usage
Person p = new Person("John", 25);
p.name(); // "John" (accessor)
p.age(); // 25
// Auto-generated: constructor, getters,
// equals(), hashCode(), toString()
Enums
enum Day {
MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
// Enum with values
enum Status {
ACTIVE(1), INACTIVE(0);
private final int code;
Status(int code) {
this.code = code;
}
public int getCode() { return code; }
}
Day day = Day.MONDAY;
day.name(); // "MONDAY"
day.ordinal(); // 0
Exception Handling
Try-Catch-Finally
try {
// Risky code
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
// Catch all other exceptions
e.printStackTrace();
} finally {
// Always executes
System.out.println("Cleanup");
}
// Multi-catch (Java 7+)
catch (IOException | SQLException e) { }
Try-with-Resources
// Auto-closes resources (Java 7+)
try (
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr)
) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
// Resources auto-closed here
Throw & Throws
// throws - declare exceptions
public void readFile(String path)
throws FileNotFoundException, IOException {
FileReader fr = new FileReader(path);
}
// throw - throw exception
public void validate(int age) {
if (age < 0) {
throw new IllegalArgumentException(
"Age cannot be negative");
}
}
Custom Exception
// Checked exception
class CustomException extends Exception {
public CustomException(String msg) {
super(msg);
}
}
// Unchecked exception
class CustomRuntimeException
extends RuntimeException {
public CustomRuntimeException(String msg) {
super(msg);
}
}
// Usage
throw new CustomException("Error occurred");
Collections Framework
List
// ArrayList (most used)
List<String> list = new ArrayList<>();
list.add("A");
list.add(0, "B"); // Add at index
list.get(0); // Get element
list.set(0, "C"); // Update
list.remove(0); // Remove by index
list.remove("A"); // Remove by value
list.size(); // Size
list.contains("A"); // Check existence
list.indexOf("A"); // Find index
list.isEmpty(); // Check empty
list.clear(); // Remove all
// Immutable list (Java 9+)
List<String> immutable = List.of("A", "B", "C");
Set
// HashSet (no order, fast)
Set<String> hashSet = new HashSet<>();
// LinkedHashSet (insertion order)
Set<String> linkedSet = new LinkedHashSet<>();
// TreeSet (sorted)
Set<String> treeSet = new TreeSet<>();
// Operations
set.add("A");
set.remove("A");
set.contains("A");
set.size();
// Set operations
set1.addAll(set2); // Union
set1.retainAll(set2); // Intersection
set1.removeAll(set2); // Difference
// Immutable set
Set<String> immutable = Set.of("A", "B");
Map
// HashMap (no order, fast)
Map<String, Integer> map = new HashMap<>();
// Operations
map.put("A", 1);
map.get("A"); // Returns 1
map.getOrDefault("B", 0); // Default if missing
map.remove("A");
map.containsKey("A");
map.containsValue(1);
map.keySet(); // All keys
map.values(); // All values
map.entrySet(); // All entries
// Iterate
for (Map.Entry<String, Integer> e : map.entrySet()) {
e.getKey();
e.getValue();
}
map.forEach((k, v) -> System.out.println(k + ":" + v));
// Immutable map
Map<String, Integer> m = Map.of("A", 1, "B", 2);
Queue & Deque
// Queue (FIFO)
Queue<String> queue = new LinkedList<>();
queue.offer("A"); // Add to tail
queue.poll(); // Remove from head
queue.peek(); // View head
// PriorityQueue (min-heap)
Queue<Integer> pq = new PriorityQueue<>();
// Deque (double-ended)
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("A");
deque.addLast("B");
deque.removeFirst();
deque.removeLast();
// As Stack
deque.push("A"); // addFirst
deque.pop(); // removeFirst
Collections Utility
// Sorting
Collections.sort(list);
Collections.sort(list, Collections.reverseOrder());
list.sort(Comparator.comparing(String::length));
// Searching
Collections.binarySearch(sortedList, key);
// Shuffle, Reverse, Fill
Collections.shuffle(list);
Collections.reverse(list);
Collections.fill(list, value);
// Min, Max
Collections.min(list);
Collections.max(list);
// Thread-safe wrappers
List<String> syncList =
Collections.synchronizedList(new ArrayList<>());
// Unmodifiable
List<String> readOnly =
Collections.unmodifiableList(list);
Comparator
// Lambda comparator
list.sort((a, b) -> a.compareTo(b));
list.sort((a, b) -> a.length() - b.length());
// Method reference
list.sort(Comparator.naturalOrder());
list.sort(Comparator.reverseOrder());
// Comparing methods
Comparator<Person> byName =
Comparator.comparing(Person::getName);
Comparator<Person> byAge =
Comparator.comparingInt(Person::getAge);
// Chaining
Comparator<Person> comp =
Comparator.comparing(Person::getName)
.thenComparingInt(Person::getAge)
.reversed();
Streams & Lambdas
Lambda Expressions
// Syntax
(params) -> expression
(params) -> { statements; }
// Examples
() -> 42 // No params
x -> x * 2 // Single param
(x, y) -> x + y // Multiple params
(String s) -> s.length() // Explicit type
(x, y) -> { return x + y; } // Block
// Functional interfaces
Runnable r = () -> System.out.println("Hi");
Comparator<String> c = (a, b) -> a.compareTo(b);
Predicate<Integer> p = n -> n > 0;
Function<String, Integer> f = s -> s.length();
Consumer<String> con = s -> System.out.println(s);
Supplier<Double> sup = () -> Math.random();
Method References
// Static method
Integer::parseInt
Math::abs
// Instance method (specific object)
System.out::println
str::toUpperCase
// Instance method (any object)
String::length
String::toUpperCase
// Constructor
ArrayList::new
Person::new
// Examples
list.forEach(System.out::println);
list.stream().map(String::toUpperCase);
list.stream().map(Integer::parseInt);
Stream Creation
// From Collection
list.stream()
list.parallelStream()
// From Array
Arrays.stream(array)
Stream.of("a", "b", "c")
// Generate/Iterate
Stream.generate(Math::random).limit(10)
Stream.iterate(0, n -> n + 1).limit(10)
Stream.iterate(0, n -> n < 10, n -> n + 1)
// Primitive streams
IntStream.range(0, 10) // 0-9
IntStream.rangeClosed(1, 10) // 1-10
// Empty stream
Stream.empty()
Intermediate Operations
// Filter - keep matching elements
.filter(x -> x > 0)
// Map - transform elements
.map(x -> x * 2)
.mapToInt(String::length)
// FlatMap - flatten nested
.flatMap(list -> list.stream())
// Sort
.sorted()
.sorted(Comparator.reverseOrder())
// Distinct - remove duplicates
.distinct()
// Limit & Skip
.limit(5)
.skip(2)
// Peek - debug/inspect
.peek(System.out::println)
Terminal Operations
// forEach
.forEach(System.out::println)
// Collect to collection
.collect(Collectors.toList())
.collect(Collectors.toSet())
.toList() // Java 16+
// Reduce - combine elements
.reduce(0, (a, b) -> a + b)
.reduce(Integer::sum)
// Count, Min, Max
.count()
.min(Comparator.naturalOrder())
.max(Comparator.naturalOrder())
// Find
.findFirst()
.findAny()
// Match
.anyMatch(x -> x > 0)
.allMatch(x -> x > 0)
.noneMatch(x -> x > 0)
// To array
.toArray(String[]::new)
Collectors
// Basic collectors
Collectors.toList()
Collectors.toSet()
Collectors.toCollection(TreeSet::new)
// Joining strings
Collectors.joining(", ")
Collectors.joining(", ", "[", "]")
// Counting
Collectors.counting()
// Summarizing
Collectors.summarizingInt(String::length)
// Grouping
Collectors.groupingBy(String::length)
Collectors.groupingBy(s -> s.charAt(0),
Collectors.counting())
// Partitioning
Collectors.partitioningBy(x -> x > 0)
// To Map
Collectors.toMap(
Person::getName,
Person::getAge
)
Optional
// Creating
Optional.empty()
Optional.of(value) // Non-null
Optional.ofNullable(value) // May be null
// Checking
opt.isPresent()
opt.isEmpty() // Java 11+
opt.ifPresent(v -> use(v))
// Getting value
opt.get() // Throws if empty
opt.orElse(defaultValue)
opt.orElseGet(() -> compute())
opt.orElseThrow()
opt.orElseThrow(() -> new Exception())
// Transform
opt.map(String::toUpperCase)
opt.flatMap(this::findById)
opt.filter(s -> s.length() > 5)
// Stream
opt.stream() // Java 9+
Complete Stream Example
List<String> names = Arrays.asList(
"John", "Jane", "Bob", "Alice");
// Complex pipeline
Map<Integer, List<String>> byLength = names.stream()
.filter(s -> s.length() >= 3)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.groupingBy(String::length));
// Parallel processing
long count = list.parallelStream()
.filter(s -> s.startsWith("A"))
.count();
// Find and process
names.stream()
.filter(n -> n.startsWith("J"))
.findFirst()
.ifPresent(System.out::println);
Multithreading
Creating Threads
// Method 1: Extend Thread
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running");
}
}
new MyThread().start();
// Method 2: Implement Runnable
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running");
}
}
new Thread(new MyRunnable()).start();
// Method 3: Lambda
new Thread(() -> {
System.out.println("Lambda thread");
}).start();
Thread Methods
// Starting
thread.start(); // Start thread
thread.run(); // DON'T - runs in current thread
// Pausing
Thread.sleep(1000); // Sleep for 1 second
Thread.yield(); // Hint to scheduler
// Waiting
thread.join(); // Wait for thread to finish
thread.join(1000); // Wait with timeout
// Info
thread.getName();
thread.setName("MyThread");
thread.getPriority();
thread.isAlive();
thread.getState();
Thread.currentThread();
// Daemon
thread.setDaemon(true);
thread.isDaemon();
Synchronization
// Synchronized method
public synchronized void increment() {
count++;
}
// Synchronized block
public void increment() {
synchronized (this) {
count++;
}
}
// Synchronized on specific object
private final Object lock = new Object();
synchronized (lock) {
// Critical section
}
// Static synchronization
public static synchronized void method() {
// Locks on Class object
}
wait/notify
// Producer-Consumer pattern
synchronized (lock) {
while (!condition) {
lock.wait(); // Release lock, wait
}
// Process
lock.notify(); // Wake one thread
lock.notifyAll(); // Wake all threads
}
// Rules:
// - Must be in synchronized block
// - Must own the lock
// - Use while, not if (spurious wakeup)
ExecutorService
// Creating executors
ExecutorService exec =
Executors.newFixedThreadPool(4);
ExecutorService single =
Executors.newSingleThreadExecutor();
ExecutorService cached =
Executors.newCachedThreadPool();
// Submit tasks
exec.execute(() -> doTask()); // Runnable
Future<Integer> f = exec.submit(() -> {
return 42; // Callable
});
// Get result
Integer result = f.get(); // Blocking
Integer result = f.get(1, TimeUnit.SECONDS);
// Shutdown
exec.shutdown(); // Graceful
exec.shutdownNow(); // Force
exec.awaitTermination(5, TimeUnit.SECONDS);
Thread States
// Thread.State enum
NEW // Created, not started
RUNNABLE // Running or ready to run
BLOCKED // Waiting for lock
WAITING // wait(), join()
TIMED_WAITING // sleep(), wait(timeout)
TERMINATED // Finished execution
// Check state
Thread.State state = thread.getState();
// Lifecycle:
// NEW -> start() -> RUNNABLE
// RUNNABLE -> wait() -> WAITING
// WAITING -> notify() -> RUNNABLE
// RUNNABLE -> sleep() -> TIMED_WAITING
// RUNNABLE -> run() ends -> TERMINATED
Volatile & Atomic
// Volatile - visibility only
private volatile boolean running = true;
public void stop() {
running = false; // Visible to all threads
}
public void run() {
while (running) {
// Do work
}
}
// Atomic - visibility + atomicity
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet(); // Thread-safe ++
counter.get();
counter.set(10);
counter.compareAndSet(10, 20); // CAS
// Other atomics
AtomicLong, AtomicBoolean, AtomicReference
Common Patterns
// Thread-safe singleton
public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
// CompletableFuture (Java 8+)
CompletableFuture.supplyAsync(() -> fetchData())
.thenApply(data -> process(data))
.thenAccept(result -> display(result))
.exceptionally(ex -> handleError(ex));