Java

Java Cheat Sheets

This Java cheat sheet includes symbols, ranges, grouping, assertions, and sample patterns.

Getting Started

// Hello World

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

// 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();

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
Casting between 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

Control Flow

// if-else Statement

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

// 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");
}
Switch-case branching

// for Loop

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

// Enhanced for Loop

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

// while Loop

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

// do-while Loop

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

// Loop Control Keywords

break
Exit the loop
continue
Skip to next iteration

Arrays

// Array Declaration

int[] arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
Declare and initialize array

// Array Initialization

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

// Iterate Array

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

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));
Using ArrayList

// 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"));
Using HashMap

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");
    }
}
Defining a class

// Object Instantiation

Car car = new Car("Toyota");
car.start();
Creating an object

// 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!");
    }
}
Extending a class

// Interface

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

// Abstract Class

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

// 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

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;
    }
}
Singleton implementation

// 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();
    }
}
Factory implementation

Java 8+ and Functional Programming

// Lambda Expression

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

// 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();
Stream operations

// Optional

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

// Method Reference

list.forEach(System.out::println);
Reference to a method

// 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)

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");
}
Basic exception handling

// Custom Exception

public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}
Defining your own exception

// try-with-resources

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

// Common Exceptions

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

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);
    }
}
Read file with BufferedReader

// Writing to a File

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

// NIO Files API

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

// 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();
Serialize and deserialize object

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();
Extending Thread and implementing Runnable

// ExecutorService

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

// Synchronization

synchronized(this) {
    // critical section
}
Synchronized block

// Locks & Atomic

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

Land the career of your dreams!

Get inspired, learn, join competitions and grow in your job!

Sign up now