DEV Community

Cover image for Java Cheat Sheet
Mohd Helmi Aziz
Mohd Helmi Aziz

Posted on

Java Cheat Sheet

1. BASICS:

// Package declaration (optional)
package mypackage;

// Import statements
import java.util.*;

// Main class
public class Main {
    public static void main(String[] args) {
        // This is a single-line comment

        /*
           Multi-line comment:
           Declaring a string variable and printing it
        */
        String greeting = "Hello, Mie!";
        System.out.println(greeting);
    }
}
Enter fullscreen mode Exit fullscreen mode

2. VARIABLES & CONSTANTS:

public class Main {
    public static void main(String[] args) {
        // Explicit type
        int x = 42;
        String name = "Alice";

        // Type inference (Java 10+)
        var y = 10;
        var greeting = "Hello";

        // Multiple variables of the same type
        int a = 1, b = 2, c = 3;

        // Constants (final)
        final double Pi = 3.14159;
        final String Greeting = "Hello World";

        // Print examples
        System.out.println(x + ", " + name);
        System.out.println(y + ", " + greeting);
        System.out.println(a + ", " + b + ", " + c);
        System.out.println(Pi + ", " + Greeting);
        System.out.println(StatusOK + ", " + StatusNotFound);
    }
}
Enter fullscreen mode Exit fullscreen mode

3. DATA TYPES:

public class Main {
    public static void main(String[] args) {

        // Boolean
        boolean b = true;

        // String
        String s = "Hello";

        // Integers
        byte i8 = -128;             // 8-bit
        short i16 = -32768;         // 16-bit
        int i32 = -2147483648;      // 32-bit
        long i64 = -9223372036854775808L; // 64-bit

        // Note: Java does NOT have unsigned types (except char)
        char u16 = 65535;           // 16-bit unsigned, Unicode character

        // Floating Point
        float f32 = 3.14f;           // 32-bit
        double f64 = 3.14159265359;  // 64-bit

        // Complex numbers not built-in in Java; need libraries like Apache Commons Math

        // Char (alias for Unicode code point, 16-bit unsigned)
        char r = '世';

        // Byte (8-bit signed)
        byte by = 'A';

        // Print examples
        System.out.println("Boolean: " + b);
        System.out.println("String: " + s);
        System.out.println("Integers: " + i8 + ", " + i16 + ", " + i32 + ", " + i64);
        System.out.println("Char: " + r);
        System.out.println("Byte: " + by);
        System.out.println("Floating Point: " + f32 + ", " + f64);
    }
}
Enter fullscreen mode Exit fullscreen mode

4. OPERATORS:

public class Main {
    public static void main(String[] args) {

        // --- Arithmetic Operators ---
        int a = 10, b = 3;
        System.out.println(a + b); // addition → 13
        System.out.println(a - b); // subtraction → 7
        System.out.println(a * b); // multiplication → 30
        System.out.println(a / b); // division → 3
        System.out.println(a % b); // modulus → 1
        a++; // increment
        b--; // decrement

        // --- Relational (Comparison) Operators ---
        System.out.println(a == b); // equal to
        System.out.println(a != b); // not equal to
        System.out.println(a > b);  // greater than
        System.out.println(a < b);  // less than
        System.out.println(a >= b); // greater or equal
        System.out.println(a <= b); // less or equal

        // --- Logical Operators ---
        boolean x = true, y = false;
        System.out.println(x && y); // AND → false
        System.out.println(x || y); // OR → true
        System.out.println(!x);     // NOT → false

        // --- Bitwise Operators ---
        int m = 6, n = 3;           // 6 = 110, 3 = 011
        System.out.println(m & n);   // AND → 2
        System.out.println(m | n);   // OR → 7
        System.out.println(m ^ n);   // XOR → 5
        System.out.println(~m);      // NOT → -7
        System.out.println(m << 1);  // left shift → 12
        System.out.println(m >> 1);  // right shift → 3
        System.out.println(m >>> 1); // unsigned right shift → 3

        // --- Assignment Operators ---
        int c = 5;
        c += 3; // c = 8
        c -= 2; // c = 6
        c *= 4; // c = 24
        c /= 6; // c = 4
        c %= 3; // c = 1
        System.out.println(c);

        // --- Other Operators ---
        int max = (a > b) ? a : b; // ternary operator
        System.out.println(max);

        String str = "Hello";
        boolean check = str instanceof String; // type check
        System.out.println(check); // true
    }
}
Enter fullscreen mode Exit fullscreen mode

5. CONTROL STRUCTURES:

public class Main {
    public static void main(String[] args) {

        // --- If / Else ---
        int x = 10;
        if (x > 5) {                         // if condition
            System.out.println("x > 5");
        } else if (x == 5) {                  // else-if condition
            System.out.println("x == 5");
        } else {                              // else
            System.out.println("x < 5");
        }

        // --- Switch ---
        int day = 3;
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;                        // break to prevent fall-through
            case 2:
            case 3:
                System.out.println("Tue or Wed");
                break;
            default:
                System.out.println("Other day");
        }

        // Expression-less switch alternative: use if-else
        int num = 15;
        if (num % 2 == 0) {
            System.out.println("Even");
        } else {
            System.out.println("Odd");
        }

        // --- Classic For Loop ---
        for (int i = 0; i < 3; i++) {         // initialize; condition; increment
            System.out.println(i);
        }

        // --- While Loop ---
        int j = 0;
        while (j < 3) {                       // condition
            System.out.println(j);
            j++;                               // increment inside loop
        }

        // --- Do-While Loop ---
        int k = 0;
        do {
            System.out.println(k);
            k++;
        } while (k < 3);                     // check condition after loop

        // --- Infinite Loop ---
        // for (;;) { System.out.println("loop"); } // runs forever

        // --- For-each Loop (like Go range) ---
        int[] nums = {10, 20, 30};           // array
        for (int val : nums) {               // for-each iteration
            System.out.println(val);
        }

        java.util.Map<String, Integer> map = java.util.Map.of("a", 1, "b", 2); // map
        for (java.util.Map.Entry<String, Integer> entry : map.entrySet()) {   // iterate map
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        String str = "Java";                  // string iteration
        for (int i = 0; i < str.length(); i++) {
            char r = str.charAt(i);          // get character at index
            System.out.println(i + ":" + r);
        }

        // --- Break / Continue ---
        for (int i = 0; i < 5; i++) {
            if (i == 2) continue;            // skip current iteration
            if (i == 4) break;               // exit loop
            System.out.println(i);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

6. COLLECTIONS:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {

        // --- Array ---
        // Fixed size, elements of the same type
        int[] arr = {1, 2, 3};             // create array
        System.out.println(arr[0]);        // access element → 1

        // --- ArrayList ---
        // Dynamic size, elements of the same type
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");                  // add element
        list.add("Python");
        list.add("C++");
        list.add("Rust");
        System.out.println(list.get(0));   // access element → "Java"

        // --- HashMap ---
        // Key-value pairs (unordered)
        HashMap<String, Integer> map = new HashMap<>();
        map.put("Alice", 25);
        map.put("Bob", 30);
        System.out.println(map.get("Alice")); // access value → 25

        // --- Iteration examples ---

        // Array
        for (int val : arr) {
            System.out.println(val);
        }

        // ArrayList
        for (String val : list) {
            System.out.println(val);
        }

        // HashMap
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

7. METHODS:

import java.util.function.BiFunction;
import java.util.function.Function;

public class Main {

    public static void main(String[] args) {

        // --- Basic method ---
        int sum = add(3, 5);               // call method
        System.out.println(sum);           // 8

        // --- Multiple return values (simulated using array) ---
        int[] result = divide(10, 3);     // returns quotient and remainder
        System.out.println("Quotient: " + result[0] + ", Remainder: " + result[1]); // 3, 1

        // --- Variadic method ---
        int total = sumAll(1, 2, 3, 4);   // pass multiple arguments
        System.out.println(total);        // 10

        // --- Method as value (using functional interface) ---
        BiFunction<Integer, Integer, Integer> f = Main::add; // reference to method
        int res = f.apply(10, 20);
        System.out.println(res);          // 30

        // --- Anonymous function / Lambda ---
        Function<String, String> greet = (name) -> "Hello " + name;
        String msg = greet.apply("Java");
        System.out.println(msg);          // Hello Java
    }

    // Basic method
    static int add(int a, int b) {
        return a + b;
    }

    // Simulate multiple return values using array
    static int[] divide(int a, int b) {
        int q = a / b;
        int r = a % b;
        return new int[]{q, r};
    }

    // Variadic method
    static int sumAll(int... nums) {
        int total = 0;
        for (int n : nums) {
            total += n;
        }
        return total;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)