☕ Java Programming
Java Complete Cheatsheet
OOP, collections, streams, lambdas, file I/O and concurrency — complete Java reference.
01
Syntax & Types
▼
JAVAJava basics
// File: Main.java — class name MUST match filename
public class Main {
public static void main(String[] args) {
// Primitives
int age = 22;
double pi = 3.14159;
char grade = 'A';
boolean active = true;
long bigNum = 9999999999L;
float temp = 98.6f;
// Strings (immutable objects)
String name = "Ali";
String greeting = "Hello " + name;
String fmt = String.format("Age: %d, GPA: %.2f", age, pi);
int len = name.length();
String upper = name.toUpperCase();
boolean has = name.contains("A");
String[] parts = "a,b,c".split(",");
// Arrays
int[] nums = {1, 2, 3, 4, 5};
int[] zeros = new int[10]; // default 0
String[] names = new String[5];
System.out.println(nums.length);
// Input
java.util.Scanner sc = new java.util.Scanner(System.in);
String input = sc.nextLine();
int n = sc.nextInt();
}
}
💡
Java is strongly typed and compiled. Every class goes in its own file (public classes). JVM runs bytecode — write once, run anywhere.
02
OOP Fundamentals
▼
JAVAOOP — Classes and Objects
public class BankAccount {
// Fields
private String owner; // encapsulation — private
private double balance;
private static int count = 0; // shared across all instances
// Constructor
public BankAccount(String owner, double initialBalance) {
this.owner = owner;
this.balance = initialBalance;
count++;
}
// Methods
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public boolean withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
return true;
}
return false;
}
// Getters
public double getBalance() { return balance; }
public String getOwner() { return owner; }
public static int getCount() { return count; }
// toString override
@Override
public String toString() {
return String.format("%s: $%.2f", owner, balance);
}
}
// Usage
BankAccount acc = new BankAccount("Ali", 1000.0);
acc.deposit(500);
acc.withdraw(200);
System.out.println(acc); // Ali: $1300.00
03
Inheritance & Polymorphism
▼
JAVAInheritance & Polymorphism
// Parent class
public abstract class Shape {
protected String color;
public Shape(String color) { this.color = color; }
public abstract double area(); // must be implemented by children
public String describe() {
return color + " shape with area " + area();
}
}
// Child classes
public class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color); // call parent constructor first
this.radius = radius;
}
@Override
public double area() { return Math.PI * radius * radius; }
}
public class Rectangle extends Shape {
private double w, h;
public Rectangle(String color, double w, double h) {
super(color);
this.w = w; this.h = h;
}
@Override
public double area() { return w * h; }
}
// Polymorphism
Shape[] shapes = { new Circle("red", 5), new Rectangle("blue", 4, 6) };
for (Shape s : shapes) {
System.out.println(s.describe()); // calls correct area()!
}
@Override
Annotation tells compiler you're overriding. Catches typos.
super
Call parent constructor/method: super(), super.method()
final class
Cannot be extended. String is final.
final method
Cannot be overridden by subclasses.
instanceof
if (s instanceof Circle c) — pattern matching (Java 16+)
04
Interfaces & Abstract
▼
JAVAInterfaces
// Interface — contract with only method signatures (Java 8+ allows defaults)
public interface Printable {
void print(); // abstract by default
default void printTwice() { // default method (Java 8+)
print();
print();
}
static void info() { System.out.println("Printable interface"); }
}
public interface Saveable {
boolean save(String path);
}
// Implement multiple interfaces
public class Document implements Printable, Saveable {
private String content;
public Document(String content) { this.content = content; }
@Override
public void print() { System.out.println(content); }
@Override
public boolean save(String path) {
// write to file
return true;
}
}
// Functional interface (1 abstract method) + lambda
@FunctionalInterface
interface Transformer {
String transform(String input);
}
Transformer upper = s -> s.toUpperCase();
Transformer rev = s -> new StringBuilder(s).reverse().toString();
System.out.println(upper.transform("hello")); // HELLO
💡
Java classes can extend ONE class but implement MULTIPLE interfaces. Prefer interfaces over abstract classes for flexibility.
05
Collections Framework
▼
JAVACollections Framework
import java.util.*; import java.util.stream.*; // List (ordered, allows duplicates) Listlist = new ArrayList<>(); list.add("Ali"); list.add("Sara"); list.add("Ali"); list.get(0); list.size(); list.contains("Ali"); Collections.sort(list); list.sort(Comparator.reverseOrder()); // Set (unique values) Set set = new HashSet<>(Arrays.asList(1,2,3,2,1)); // {1,2,3} Set sorted = new TreeSet<>(set); // sorted // Map (key-value pairs) Map map = new HashMap<>(); map.put("apple", 5); map.get("apple"); // 5 map.getOrDefault("banana", 0); // 0 map.containsKey("apple"); // true map.forEach((k, v) -> System.out.println(k + ": " + v)); // Queue and Deque Queue q = new LinkedList<>(); q.offer("first"); q.poll(); q.peek(); Deque deque = new ArrayDeque<>(); deque.addFirst(1); deque.addLast(2); deque.peekFirst(); // LinkedList (doubly-linked) LinkedList ll = new LinkedList<>(); ll.addFirst("start"); ll.addLast("end");
💡
Use ArrayList for most cases. LinkedList if you frequently insert/delete in middle. HashMap for O(1) lookup.
06
Exception Handling
▼
JAVAException handling
// Try-catch-finally
try {
int result = 10 / 0;
String s = null;
s.length(); // NullPointerException
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("Null error: " + e.getMessage());
} catch (Exception e) {
System.out.println("General error: " + e.getMessage());
} finally {
System.out.println("Always runs — for cleanup");
}
// Custom exception
public class InsufficientFundsException extends RuntimeException {
private final double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds: need " + amount + " more");
this.amount = amount;
}
public double getAmount() { return amount; }
}
// Throw
throw new InsufficientFundsException(500.0);
// Multi-catch (Java 7+)
try { ... } catch (IOException | SQLException e) { ... }
// Try-with-resources (auto-close)
try (FileReader fr = new FileReader("file.txt")) {
// fr.close() called automatically
}
⚠️
Catch specific exceptions before general ones. Never catch Exception silently — always log or rethrow.
07
Streams & Lambda
▼
JAVAStreams & Lambdas (Java 8+)
import java.util.stream.*; import java.util.*; Listnames = Arrays.asList("Ali", "Sara", "Bob", "Zara", "Ali"); // Stream pipeline names.stream() .filter(n -> n.length() > 2) // keep length > 2 .map(String::toUpperCase) // transform .sorted() // sort alphabetically .distinct() // remove duplicates .limit(5) // max 5 results .forEach(System.out::println); // Collect to List List result = names.stream() .filter(n -> n.startsWith("A")) .collect(Collectors.toList()); // Collect to Map Map nameLengths = names.stream() .collect(Collectors.toMap(n -> n, String::length)); // Aggregation long count = names.stream().filter(n -> n.length() > 3).count(); Optional first = names.stream().findFirst(); boolean anyMatch = names.stream().anyMatch(n -> n.startsWith("A")); // Numeric streams int sum = IntStream.rangeClosed(1, 100).sum(); // 1 to 100 Optional max = IntStream.of(3,1,4,1,5).max(); // Parallel stream names.parallelStream().filter(n -> n.length() > 2).collect(Collectors.toList());
💡
Streams are lazy — operations only run when a terminal operation (collect, count, forEach) is called. Use parallelStream() carefully.
08
File I/O
▼
JAVAFile I/O (Modern)
import java.nio.file.*;
import java.io.*;
import java.util.List;
// Read entire file
String content = Files.readString(Path.of("file.txt"));
List lines = Files.readAllLines(Path.of("file.txt"));
// Write file
Files.writeString(Path.of("output.txt"), "Hello, World!");
Files.write(Path.of("out.txt"), lines);
// Append to file
Files.writeString(Path.of("log.txt"), "New line\n",
StandardOpenOption.APPEND, StandardOpenOption.CREATE);
// Check existence
Files.exists(Path.of("file.txt"));
Files.isDirectory(Path.of("/home"));
// Copy and move
Files.copy(Path.of("src.txt"), Path.of("dst.txt"),
StandardCopyOption.REPLACE_EXISTING);
Files.move(Path.of("old.txt"), Path.of("new.txt"));
// Delete
Files.delete(Path.of("file.txt"));
Files.deleteIfExists(Path.of("maybe.txt"));
// List directory
Files.list(Path.of(".")).forEach(System.out::println);
// Walk directory tree
Files.walk(Path.of("./src"))
.filter(p -> p.toString().endsWith(".java"))
.forEach(System.out::println);
💡
Prefer java.nio.file.Files (Java 7+) over old java.io.File. Much cleaner API.
09
Concurrency Basics
▼
JAVAConcurrency basics
import java.util.concurrent.*;
// Thread — basic way
Thread t = new Thread(() -> {
System.out.println("Running in thread: " + Thread.currentThread().getName());
});
t.start();
t.join(); // wait for thread to finish
// ExecutorService — better way
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> { /* task 1 */ });
executor.submit(() -> { /* task 2 */ });
executor.shutdown();
executor.awaitTermination(60, TimeUnit.SECONDS);
// Callable — returns result
Callable task = () -> {
Thread.sleep(1000);
return 42;
};
Future future = executor.submit(task);
Integer result = future.get(); // blocks until done
// CompletableFuture (async pipelines)
CompletableFuture.supplyAsync(() -> fetchUser(id))
.thenApply(user -> user.getName())
.thenAccept(name -> System.out.println("Name: " + name))
.exceptionally(e -> { System.out.println("Error: " + e); return null; });
// synchronized keyword
public synchronized void increment() { count++; }
// ConcurrentHashMap — thread-safe map
ConcurrentHashMap map = new ConcurrentHashMap<>();
AtomicInteger atomic = new AtomicInteger(0);
atomic.incrementAndGet();
⚠️
Avoid shared mutable state. Use synchronized, locks, or atomic classes for thread-safe operations.
10
Mini Quizzes
▼
❓ Quiz 1
What is the difference between an interface and an abstract class in Java?
A class can extend ONE class (abstract or concrete) but implement MULTIPLE interfaces. Interfaces define a contract; abstract classes can have state and shared implementation.
❓ Quiz 2
What does the Stream filter() method return?
filter() is an intermediate stream operation — it returns a new Stream. Streams are lazy; no work happens until a terminal operation like collect(), count(), or forEach() is called.