Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Java Basics

    Quick Reference

    Glossary and cheat sheet for Java Basics — the page to reread before an interview.

    Extra: Reference8 min read

    Glossary#

    TermPlain meaningChapter
    JDK / JRE / JVMdev kit / runtime (JVM + library) / the bytecode runner1
    LTSlong-term support Java version (8, 11, 17, 21, 25)1
    class / main methodcontainer for code / where running starts1
    statement / blockone instruction ending in ; / code inside { }1
    compile error / runtime error (exception)caught by javac / happens while running1
    variable / typenamed box / what kind of value it holds2
    declare / assign / initialisecreate the box / put a value in / both at once2
    statically typedtypes fixed and checked at compile time2
    primitive typebyte short int long float double boolean char2
    literala value written in code (200, 9L, 'A', "A")2
    final / constantassign once / a fixed named value2
    camelCase / PascalCase / UPPER_SNAKE_CASEvariables & methods / classes / constants2
    operator / expressioncombines values / anything producing a value3
    integer division / modulo (%)drops the fraction / the remainder3
    pre- / post-increment++i changes first / i++ gives old value first3
    short-circuit&&/|| skip the right side when the answer is known3
    widening / narrowing / castsmall→big automatic / big→small / explicit (type) conversion3
    String / concatenationtext object / joining with +4
    format specifier%d %s %.2f %n placeholders in printf4
    parsingtext → number (Integer.parseInt)4
    if / else if / else / ternary / switchdecisions5
    fall-throughold switch running into the next case without break5
    for / while / do-while / for-eachloops6
    break / continue / labelleave loop / next round / exit an outer loop6
    off-by-one errorloop runs one step too many or too few6
    method / signaturenamed reusable code / its name + parameters7
    parameter / argumentdeclared input / actual value passed7
    return type / voidtype of the result / no result7
    scopewhere a variable exists7
    pass-by-valuethe variable's value (number or reference) is copied7
    overloadingsame method name, different parameter lists7
    array / element / indexfixed row of same-type values / one value / its 0-based position8
    null"refers to nothing"8
    ArrayIndexOutOfBoundsExceptionreading/writing outside 0..length-18
    aliasingtwo variables referring to the same array8
    2-D arrayan array of arrays (a grid)8
    stdin / stdout, BufferedReader, StringBuilderinput/output streams, fast reader, fast string building9

    Cheat Sheet#

    Skeleton

    Java
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            // ...
        }
    }
    // run: java Main.java

    Types and limits

    Output
      int ±2.1e9 (default) · long ±9.2e18 (9_000_000_000L) · double (default decimal) · boolean · char ('A' = 65)
      Integer.MAX_VALUE / MIN_VALUE · Long.MAX_VALUE

    Operator traps

    Output
      7 / 2 = 3 · 7.0 / 2 = 3.5 · -7 % 3 = -1 · Math.floorMod(-7, 3) = 2
      i++ old value · ++i new value · (int) 3.99 = 3 · (double) a / b for averages
      c - 'a' → 0..25 · (char)('a' + k) → k-th letter · safe mid: lo + (hi - lo) / 2
      "x" + 1 + 2 = "x12" · strings: a.equals(b), never ==

    Loops

    Java
    for (int i = 0; i < n; i++)                 // forward
    for (int i = n - 1; i >= 0; i--)            // backward
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)         // all pairs
    while (n > 0) { n /= 10; }                  // digits
    for (int x : arr)                           // values only

    Arrays

    Java
    int[] a = new int[n];         int[] b = {1, 2, 3};          int[][] g = new int[rows][cols];
    a.length   Arrays.toString(a)   Arrays.sort(a)   Arrays.fill(a, -1)   Arrays.copyOf(a, n)   Arrays.deepToString(g)
    int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};   // grid neighbours
    int[] count = new int[26]; count[c - 'a']++;  // letter counts

    Strings

    Java
    s.length()  s.charAt(i)  s.substring(a, b)  s.indexOf("x")  s.equals(t)  s.split(" ")
    Integer.parseInt("42")   String.valueOf(42)   System.out.printf("%d %.2f %s%n", n, d, s);

    Fast I/O (competitive programming)

    Java
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer(br.readLine());
    int x = Integer.parseInt(st.nextToken());
    StringBuilder out = new StringBuilder(); ... System.out.print(out);

    Try This Yourself#

    1. Type and run every program in this file. For each, predict the output first; when you're wrong, find which chapter explains why.

    2. FizzBuzz, then extend it. Print 1 to 30, but "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both. Then write a method static String fizz(int n) that returns the word instead of printing it, and call it from a loop.

    3. Extend the StudyBuddy report. (a) Print how many students passed (≥ PASS_MARK). (b) Handle ties: print every student who has the top score. (c) Count how many students got each grade using an int[3]. (d) Read the names and answer counts from stdin using the fast input template.

    4. Grid practice. Create a 5×5 int[][] grid, set a few cells to 1, and for the centre cell print how many of its 4 neighbours are 1 — using the dirs pattern with the bounds check.