ENGIMY.IO - CHEATSHEET
JAVA × QUICK REFERENCE
REFERENCE vJava 17

Java Quick Reference

Everything you need day‑to‑day – syntax, OOP, collections, and modern features.

Data Types

Primitive Types
  • byte8‑bit integer
  • short16‑bit integer
  • int32‑bit integer
  • long64‑bit integer (L suffix)
  • float32‑bit floating point (f suffix)
  • double64‑bit floating point
  • char16‑bit Unicode
  • booleantrue / false
Reference Types
  • String
  • Arrays
  • Classes
  • Interfaces
  • Enums
  • CollectionsList, Set, Map
  • Optional<T>may contain value
  • varlocal variable type inference (Java 10+)

Type Conversion

// Implicit (widening)
int num = 10;
double d = num;           // int → double

// Explicit (narrowing) – may lose data
double d = 3.14;
int num = (int) d;        // 3

// String to primitive
int i = Integer.parseInt("123");
double d = Double.parseDouble("3.14");
boolean b = Boolean.parseBoolean("true");

// Primitive to String
String str = Integer.toString(123);
String str2 = String.valueOf(3.14);

Variables

// Declaration and initialisation
int age = 25;
String name = "Alice";
double pi = 3.14159;
boolean isActive = true;
final double TAX_RATE = 0.08;   // constant (cannot be reassigned)

// Java 10+ var – local variable type inference
var list = new ArrayList<String>();  // inferred as ArrayList<String>
var number = 42;                    // inferred as int

Control Flow

if / else if / else

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

switch (modern)

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

// Switch expression (Java 14+)
String result = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    default -> "Other";
};

Loops

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

// Enhanced for (for‑each)
int[] numbers = {1, 2, 3, 4, 5};
for (int n : numbers) {
    System.out.println(n);
}

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

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

// break / continue
for (int i = 0; i < 20; i++) {
    if (i % 2 == 0) continue;   // skip even
    if (i > 15) break;        // exit loop
    System.out.println(i);
}

Methods

Declaration

public static int add(int a, int b) {
    return a + b;
}

// Void method
public static void greet(String name) {
    System.out.println("Hello, " + name);
}

// Method overloading
public static int max(int a, int b) {
    return (a > b) ? a : b;
}
public static double max(double a, double b) {
    return (a > b) ? a : b;
}

// Varargs
public static int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) total += n;
    return total;
}

// Recursion
public static long factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

Classes & Objects

public class Person {
    // Fields (instance variables)
    private String name;
    private int age;

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

    // Default constructor
    public Person() {
        this("", 0);
    }

    // Methods
    public void introduce() {
        System.out.println("I am " + name + ", " + age + " years old");
    }

    // Getters & Setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

Inheritance

public class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public void speak() {
        System.out.println(name + " makes a sound");
    }
}

public class Dog extends Animal {
    private String breed;

    public Dog(String name, String breed) {
        super(name);
        this.breed = breed;
    }

    // Method overriding
    @Override
    public void speak() {
        System.out.println("Woof!");
    }

    public String getBreed() { return breed; }
}

Interfaces

// Interface definition
public interface Drawable {
    void draw();

    // Default method (Java 8+)
    default void print() {
        System.out.println("Drawing...");
    }

    // Static method (Java 8+)
    static void info() {
        System.out.println("Drawable interface");
    }
}

// Implementing interface
public class Circle implements Drawable {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

Exception Handling

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.err.println("Math error: " + e.getMessage());
} catch (Exception e) {
    System.err.println("Generic error: " + e.getMessage());
} finally {
    System.out.println("Always executes");
}

// Throwing exceptions
public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    this.age = age;
}

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

// Try‑with‑resources (Java 7+)
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line = br.readLine();
} catch (IOException e) {
    e.printStackTrace();
}

Collections Framework

List
  • ArrayList<T>dynamic array
  • LinkedList<T>doubly‑linked list
  • Vector<T>synchronised array
  • Stack<T>LIFO
Set
  • HashSet<T>unique, unordered
  • LinkedHashSet<T>unique, insertion order
  • TreeSet<T>unique, sorted
Map
  • HashMap<K,V>key‑value, unordered
  • LinkedHashMap<K,V>key‑value, insertion order
  • TreeMap<K,V>key‑value, sorted
  • ConcurrentHashMap<K,V>thread‑safe
Queue
  • PriorityQueue<T>priority order
  • ArrayDeque<T>double‑ended queue
  • LinkedList<T>as queue

Common Collection Operations

// ArrayList
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add(1, "Mango");
String fruit = list.get(0);
list.remove(1);
list.size();
list.isEmpty();

// HashMap
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 95);
map.put("Bob", 87);
int score = map.get("Alice");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

// HashSet
HashSet<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.contains(1);  // true

File I/O

// Reading text file (try‑with‑resources)
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// Writing to text file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
    writer.write("Hello, World!");
    writer.newLine();
    writer.write("Second line");
} catch (IOException e) {
    e.printStackTrace();
}

// Reading with Scanner
try (Scanner scanner = new Scanner(new File("data.txt"))) {
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

// Files class (Java 7+)
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
Files.write(Paths.get("output.txt"), content.getBytes());

Lambdas & Streams (Java 8+)

Lambda Expressions

// Syntax: (parameters) -> expression
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Lambda with single parameter
names.forEach(name -> System.out.println(name));

// Lambda with multiple parameters
Comparator<String> comp = (a, b) -> a.compareTo(b);

// Functional Interfaces
// Predicate<T>, Function<T,R>, Consumer<T>, Supplier<T>
Predicate<Integer> isEven = x -> x % 2 == 0;

Streams

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);

// Filter, map, collect
List<Integer> squares = numbers.stream()
    .filter(n -> n % 2 == 0)
    .map(n -> n * n)
    .collect(Collectors.toList());  // [4, 16, 36, 64]

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

// Find first match
Optional<Integer> first = numbers.stream()
    .filter(n -> n > 5)
    .findFirst();  // Optional[6]

// Grouping
Map<String, List<Person>> byCity = people.stream()
    .collect(Collectors.groupingBy(Person::getCity));

// FlatMap
List<List<Integer>> listOfLists = ...
List<Integer> flat = listOfLists.stream()
    .flatMap(List::stream)
    .collect(Collectors.toList());

Optional (Java 8+)

Optional<String> optional = Optional.of("Hello");

// Check if present
if (optional.isPresent()) {
    String value = optional.get();
}

// orElse / orElseGet
String value = optional.orElse("Default");
String value2 = optional.orElseGet(() -> "Computed Default");

// orElseThrow
String value3 = optional.orElseThrow(() -> new RuntimeException("No value"));

// map / flatMap
Optional<Integer> length = optional.map(String::length);

// ifPresent
optional.ifPresent(value -> System.out.println(value));

Common Built‑ins

String
  • s.length()
  • s.toUpperCase()
  • s.toLowerCase()
  • s.trim()
  • s.split(regex)
  • s.contains(sub)
  • s.startsWith(prefix)
  • s.endsWith(suffix)
  • s.replace(old, new)
  • s.substring(start, end)
  • s.indexOf(char)
  • s.isEmpty()
  • s.equals(other)
  • String.join(delim, array)
Math
  • Math.abs(x)
  • Math.ceil(x)
  • Math.floor(x)
  • Math.round(x)
  • Math.max(a, b)
  • Math.min(a, b)
  • Math.random()
  • Math.pow(x, y)
  • Math.sqrt(x)
  • Math.PI
  • Math.E

Array Utilities (java.util.Arrays)

int[] arr = {3, 1, 4, 1, 5};
Arrays.sort(arr);                 // sort
int index = Arrays.binarySearch(arr, 4); // binary search
String str = Arrays.toString(arr);// [1, 1, 3, 4, 5]
int[] copy = Arrays.copyOf(arr, 3); // copy first 3
boolean equal = Arrays.equals(arr1, arr2);

Enums

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

// Enum with fields and methods
public enum Status {
    SUCCESS(200, "OK"),
    NOT_FOUND(404, "Not Found"),
    ERROR(500, "Server Error");

    private int code;
    private String message;

    Status(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() { return code; }
    public String getMessage() { return message; }
}

Day today = Day.MONDAY;
for (Day d : Day.values()) { ... }

Generics

public class Box<T> {
    private T content;

    public void set(T content) { this.content = content; }
    public T get() { return content; }
}

// Wildcards
public void process(List<? extends Number> list) { ... }  // unbounded
public void add(List<? super Integer> list) { ... }     // lower bounded

Best Practices

  • Follow naming conventions: PascalCase for classes, camelCase for methods/variables, UPPER_SNAKE for constants.
  • Use private fields with getters/setters (encapsulation).
  • Prefer ArrayList over Vector unless synchronisation is needed.
  • Use try‑with‑resources for AutoCloseable resources (files, streams, etc.).
  • Use Optional instead of returning null.
  • Use StringBuilder for string concatenation in loops (or StringBuffer for thread‑safety).
  • Prefer interface over abstract class when possible.
  • Use @Override annotation when overriding methods.
  • Use equals() and hashCode() together when overriding.
  • Use List.of() and Set.of() for immutable collections (Java 9+).
  • Use var for local variables when the type is obvious (Java 10+).
  • Handle exceptions at the appropriate level – don't swallow them silently.
📌 Quick Reference
Check Java version: java -version
Compile: javac Program.java
Run: java Program
JAR creation: jar cvf app.jar *.class
Javadoc: javadoc -d docs *.java
← Back to All Cheatsheets