Skip to main content

Java Cheatsheet

Languages 17 views Apr 2026

Java Cheatsheet

Data Types & Variables

// Primitives
byte   b = 127;
short  s = 32000;
int    i = 2_000_000;
long   l = 9_000_000_000L;
float  f = 3.14f;
double d = 3.14159;
char   c = 'A';
boolean flag = true;

// Autoboxing — primitive ↔ wrapper
Integer boxed = 42;
int unboxed = boxed;

// String (immutable)
String str = "Hello";
String str2 = new String("Hello");   // avoid
String built = "Hello" + " " + "World";

// var (local type inference, Java 10+)
var list = new ArrayList<String>();
var count = 0;

String Methods

String s = "Hello, World!";
s.length()                  // 13
s.charAt(0)                 // 'H'
s.substring(7)              // "World!"
s.substring(7, 12)          // "World"
s.indexOf("World")          // 7
s.contains("World")         // true
s.startsWith("Hello")       // true
s.endsWith("!")             // true
s.toUpperCase()             // "HELLO, WORLD!"
s.toLowerCase()             // "hello, world!"
s.trim()                    // remove whitespace
s.strip()                   // Unicode-aware trim (Java 11)
s.replace("World","Java")   // "Hello, Java!"
s.split(", ")               // ["Hello", "World!"]
s.isEmpty()                 // false
s.isBlank()                 // false (Java 11)

// String.format / formatted (Java 15+)
String.format("Name: %s, Age: %d", name, age)
"Name: %s".formatted(name)

// StringBuilder (mutable)
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("World");
sb.insert(5, ",");
sb.reverse();
String result = sb.toString();

Collections

import java.util.*;

// List
List<String> list = new ArrayList<>();
list.add("a");
list.add(0, "x");           // insert at index
list.get(0);
list.set(0, "z");
list.remove("a");
list.size();
list.contains("z");
list.sort(Comparator.naturalOrder());
Collections.sort(list);
Collections.reverse(list);

// Immutable list (Java 9+)
List<String> immutable = List.of("a","b","c");

// Map
Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
map.get("key");             // 1
map.getOrDefault("x", 0);  // 0
map.containsKey("key");     // true
map.remove("key");
map.putIfAbsent("key", 2);

for (Map.Entry<String,Integer> e : map.entrySet()) {
    System.out.println(e.getKey() + "=" + e.getValue());
}

// Immutable map (Java 9+)
Map<String,Integer> m = Map.of("a",1,"b",2);

// Set
Set<String> set = new HashSet<>();
set.add("a"); set.add("b"); set.add("a");  // size = 2
Set<String> sorted = new TreeSet<>(set);

// Queue / Deque
Queue<Integer> q = new LinkedList<>();
q.offer(1); q.offer(2);
q.poll();     // removes head
q.peek();     // views head

Deque<Integer> deque = new ArrayDeque<>();

Control Flow

// if / else
if (x > 0) {
    System.out.println("positive");
} else if (x == 0) {
    System.out.println("zero");
} else {
    System.out.println("negative");
}

// Ternary
String res = (x > 0) ? "positive" : "non-positive";

// switch (classic)
switch (day) {
    case "MON": case "TUE": System.out.println("Weekday"); break;
    case "SAT": case "SUN": System.out.println("Weekend"); break;
    default: System.out.println("Unknown");
}

// switch expression (Java 14+)
String label = switch (day) {
    case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";
    case "SAT", "SUN" -> "Weekend";
    default -> "Unknown";
};

// for
for (int i = 0; i < 10; i++) { }

// enhanced for
for (String s : list) { }

// while / do-while
while (condition) { }
do { } while (condition);

OOP

// Class
public class Person {
    private String name;   // encapsulation
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters / Setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    @Override
    public String toString() {
        return "Person{name=" + name + ", age=" + age + "}";
    }
}

// Inheritance
public class Employee extends Person {
    private String company;

    public Employee(String name, int age, String company) {
        super(name, age);
        this.company = company;
    }

    @Override
    public String toString() {
        return super.toString() + ", company=" + company;
    }
}

// Interface
public interface Printable {
    void print();                         // abstract
    default void log() { System.out.println("Logging"); }  // default
    static Printable noop() { return () -> {}; }           // static
}

// Abstract class
public abstract class Shape {
    abstract double area();
    public void describe() { System.out.println("Area: " + area()); }
}

// Record (Java 16+) — immutable data carrier
public record Point(double x, double y) { }
Point p = new Point(1.0, 2.0);
p.x();  // accessor

Streams (Java 8+)

import java.util.stream.*;

List<Integer> nums = List.of(1,2,3,4,5,6,7,8,9,10);

// filter + map + collect
List<Integer> evens = nums.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());

// map + toList (Java 16+)
List<String> strs = nums.stream()
    .map(n -> "num" + n)
    .toList();

// reduce
int sum = nums.stream().reduce(0, Integer::sum);

// count / min / max / average
long count = nums.stream().filter(n -> n > 5).count();
OptionalInt max = nums.stream().mapToInt(i->i).max();
OptionalDouble avg = nums.stream().mapToInt(i->i).average();

// sorted / distinct / limit / skip
nums.stream().sorted().distinct().limit(5).skip(1).toList();

// anyMatch / allMatch / noneMatch / findFirst
boolean any = nums.stream().anyMatch(n -> n > 9);
Optional<Integer> first = nums.stream().filter(n->n>5).findFirst();

// groupingBy
Map<Boolean,List<Integer>> partitioned =
    nums.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0));

Map<Integer,List<String>> grouped = words.stream()
    .collect(Collectors.groupingBy(String::length));

// joining
String joined = Stream.of("a","b","c")
    .collect(Collectors.joining(", ", "[", "]"));  // [a, b, c]

Exception Handling

// try-catch-finally
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.err.println("Error: " + e.getMessage());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    System.out.println("Always runs");
}

// try-with-resources
try (BufferedReader br = new BufferedReader(new FileReader("f.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// Custom exception
public class AppException extends RuntimeException {
    private final int code;
    public AppException(String message, int code) {
        super(message);
        this.code = code;
    }
    public int getCode() { return code; }
}

// throws declaration
public void readFile(String path) throws IOException { }

Modern Java (8–21)

// Optional (avoid null)
Optional<String> opt = Optional.ofNullable(getValue());
opt.isPresent();
opt.orElse("default");
opt.orElseGet(() -> computeDefault());
opt.ifPresent(v -> System.out.println(v));
opt.map(String::toUpperCase).orElse("");

// Functional interfaces
Function<String, Integer> len = String::length;
Predicate<String> notEmpty = s -> !s.isEmpty();
Consumer<String> print = System.out::println;
Supplier<List<String>> listMaker = ArrayList::new;
BiFunction<Integer,Integer,Integer> add = Integer::sum;

// Method references
list.forEach(System.out::println);
list.stream().map(String::toUpperCase).toList();

// Sealed classes (Java 17+)
sealed interface Shape permits Circle, Rectangle { }
record Circle(double r) implements Shape { }
record Rectangle(double w, double h) implements Shape { }

// Pattern matching instanceof (Java 16+)
if (obj instanceof String s) {
    System.out.println(s.length());
}

// Text blocks (Java 15+)
String json = """
    {
        "name": "Alice",
        "age": 30
    }
    """;

Found this helpful? Share it!

Tweet LinkedIn WhatsApp
Translate Page