Java Cheat Sheets

Java comprehensive cheat sheet

Getting Started

Hello World

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Basic Commands

Single-line Comment
// This is a comment
Multi-line Comment
/* This is a multi-line comment */
Variable Declaration
int x = 5;
Output
System.out.println(x);
Input
Scanner sc = new Scanner(System.in); String s = sc.nextLine();

Getting Started Resources

Java Getting Started https://docs.oracle.com/javase/tutorial…
W3Schools Java https://www.w3schools.com/java/
Baeldung Java Tutorials https://www.baeldung.com/java-tutorial

Data Types

Primitive Data Types

byte
8-bit integer (-128 to 127)
short
16-bit integer (-32,768 to 32,767)
int
32-bit integer (-2^31 to 2^31-1)
long
64-bit integer (-2^63 to 2^63-1)
float
32-bit floating point
double
64-bit floating point
char
16-bit Unicode character
boolean
true or false

Type Conversion

int i = (int) 3.14; // 3
double d = 5; // 5.0

Data Types Resources

Java Data Types Docs https://docs.oracle.com/javase/tutorial…
Baeldung: Java Data Types https://www.baeldung.com/java-types

Operators

Arithmetic Operators

+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus

Comparison Operators

==
Equal to
!=
Not equal to
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to

Logical Operators

&&
Logical AND
||
Logical OR
!
Logical NOT

Operators Resources

Java Operators Docs https://docs.oracle.com/javase/tutorial…
W3Schools: Java Operators https://www.w3schools.com/java/java_ope…

Control Flow

if-else Statement

int x = 10;
if (x > 5) {
    System.out.println("Greater");
} else {
    System.out.println("Smaller or equal");
}

switch Statement

int day = 2;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    default:
        System.out.println("Other");
}

for Loop

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Enhanced for Loop

int[] arr = {1,2,3};
for (int n : arr) {
    System.out.println(n);
}

while Loop

int i = 0;
while (i < 3) {
    System.out.println(i);
    i++;
}

do-while Loop

int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 3);

Loop Control Keywords

break
Exit the loop
continue
Skip to next iteration

Control Flow Resources

Java Control Flow Docs https://docs.oracle.com/javase/tutorial…
Baeldung: Java Control Flow https://www.baeldung.com/java-control-f…

Arrays

Array Declaration

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

Array Initialization

int[] arr = {1, 2, 3};

Iterate Array

for (int n : arr) {
    System.out.println(n);
}

Arrays Resources

Java Arrays Docs https://docs.oracle.com/javase/tutorial…
W3Schools: Java Arrays https://www.w3schools.com/java/java_arr…

Collections

Common Collections

List
Ordered, allows duplicates
Set
Unordered, no duplicates
Map
Key-value pairs
Queue
FIFO structure
Stack
LIFO structure

ArrayList Example

import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
System.out.println(list.get(0));

HashMap Example

import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
System.out.println(map.get("A"));

Collections Resources

Java Collections Docs https://docs.oracle.com/javase/tutorial…
Baeldung: Java Collections https://www.baeldung.com/java-collectio…

OOP Basics

Class Definition

public class Car {
    private String brand;
    public Car(String brand) {
        this.brand = brand;
    }
    public void start() {
        System.out.println(brand + " is starting");
    }
}

Object Instantiation

Car car = new Car("Toyota");
car.start();

Inheritance

public class Animal {
    public void speak() {
        System.out.println("Animal speaks");
    }
}
public class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("Woof!");
    }
}

Interface

public interface Drawable {
    void draw();
}
public class Circle implements Drawable {
    public void draw() {
        System.out.println("Drawing Circle");
    }
}

Abstract Class

public abstract class Shape {
    abstract void draw();
}
public class Square extends Shape {
    void draw() {
        System.out.println("Drawing Square");
    }
}

OOP Principles

Encapsulation
Hiding internal state and requiring all interaction to be performed through an object’s methods
Inheritance
Mechanism for a new class to use features of another class
Polymorphism
Ability to present the same interface for different data types
Abstraction
Hiding complex reality while exposing only the necessary parts

OOP Resources

Java OOP Docs https://docs.oracle.com/javase/tutorial…
Baeldung: OOP in Java https://www.baeldung.com/java-oop

Design Patterns

Creational Patterns

Singleton
Only one instance exists
Factory
Creates objects without specifying the exact class
Builder
Constructs complex objects step by step
Prototype
Creates new objects by copying existing ones

Singleton Pattern

public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Factory Pattern

public interface Product { }
public class ConcreteProductA implements Product { }
public class ConcreteProductB implements Product { }
public class Factory {
    public Product createProduct(String type) {
        if (type.equals("A")) return new ConcreteProductA();
        else return new ConcreteProductB();
    }
}

Design Patterns Resources

Refactoring Guru: Design Patterns https://refactoring.guru/design-pattern…
Baeldung: Design Patterns https://www.baeldung.com/java-creationa…

Java 8+ and Functional Programming

Lambda Expression

List<String> list = Arrays.asList("a", "b", "c");
list.forEach(s -> System.out.println(s));

Stream API

List<Integer> nums = Arrays.asList(1,2,3,4,5);
int sum = nums.stream().filter(n -> n % 2 == 0).mapToInt(Integer::intValue).sum();

Optional

Optional<String> opt = Optional.ofNullable(null);
System.out.println(opt.orElse("default"));

Method Reference

list.forEach(System.out::println);

Functional Interfaces

Predicate<T>
boolean test(T t)
Consumer<T>
void accept(T t)
Supplier<T>
T get()
Function<T,R>
R apply(T t)
BiFunction<T,U,R>
R apply(T t, U u)

Functional Programming Resources

Java Lambda Expressions https://docs.oracle.com/javase/tutorial…
Baeldung: Java 8 Streams https://www.baeldung.com/java-8-streams
Java Optional https://www.baeldung.com/java-optional

Exception Handling

try-catch-finally

try {
    int x = 1 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} finally {
    System.out.println("Always runs");
}

Custom Exception

public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

try-with-resources

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line = br.readLine();
}

Common Exceptions

NullPointerException
Accessing a null object
ArrayIndexOutOfBoundsException
Invalid array index
ClassCastException
Invalid type cast
IOException
I/O operation failed
FileNotFoundException
File not found

Exception Handling Resources

Java Exception Handling https://docs.oracle.com/javase/tutorial…
Baeldung: Java Exceptions https://www.baeldung.com/java-exceptions

File I/O and Serialization

Reading a File

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

Writing to a File

try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"))) {
    bw.write("Hello!");
}

NIO Files API

List<String> lines = Files.readAllLines(Paths.get("file.txt"));

Serialization

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("obj.ser"));
out.writeObject(obj);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("obj.ser"));
MyClass obj2 = (MyClass) in.readObject();
in.close();

File I/O & Serialization Resources

Java File I/O https://docs.oracle.com/javase/tutorial…
Java Serialization https://docs.oracle.com/javase/tutorial…

Multithreading & Concurrency

Thread Creation

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}
new MyThread().start();
Runnable r = () -> System.out.println("Runnable running");
new Thread(r).start();

ExecutorService

ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task 1"));
executor.shutdown();

Synchronization

synchronized(this) {
    // critical section
}

Locks & Atomic

Lock lock = new ReentrantLock();
lock.lock();
try {
    // critical section
} finally {
    lock.unlock();
}
AtomicInteger ai = new AtomicInteger(0);
ai.incrementAndGet();

Concurrency Resources

Java Concurrency https://docs.oracle.com/javase/tutorial…
Baeldung: Java Concurrency https://www.baeldung.com/java-concurren…