Skip to content

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

    Java / Java Basics

    Operators

    int / int truncates toward zero. The average of scores (a + b) / 2 with ints loses the fraction. Write (a + b) / 2.0, or cast

    Chapter 3 of 98 min read

    The Plain Picture#

    The buttons on a calculator — plus a few extra: "is this bigger than that?", "are both of these true?", and "treat this decimal as a whole number".

    The Real Names#

    An operator combines values into a new value. An expression is anything that produces a value (correct * 10 + 20).

    Under the Hood#

    Arithmetic — and the integer division trap#

    Java
    System.out.println(7 / 2); // 3      ← int / int = int. The .5 is thrown away (not rounded!)
    
    System.out.println(7.0 / 2); // 3.5    ← if either side is a double, the result is a double
    
    System.out.println(7 % 3); // 1      ← % = remainder ("modulo")
    
    System.out.println(-7 % 3); // -1     ← Java's % keeps the sign of the LEFT side
    
    System.out.println(Math.floorMod(-7, 3)); // 2      ← the "maths" modulo, always 0..2 here
    • int / int truncates toward zero. The average of scores (a + b) / 2 with ints loses the fraction. Write (a + b) / 2.0, or cast (below).

    • % is used constantly in DSA: "is n even?" → n % 2 == 0; "last digit" → n % 10; "wrap around a circular array" → (i + 1) % n. With negative numbers, use Math.floorMod.

    Increment, decrement, compound assignment#

    Java
    int i = 5;
    
    int a = i++; // POST-increment: a gets the OLD value (5), then i becomes 6
    
    int b = ++i; // PRE-increment:  i becomes 7 FIRST, then b gets 7
    
    System.out.println(a + " " + b + " " + i); // 5 7 7
    Java
    points += 20; // same as points = points + 20
    
    points -= 5;
    
    points *= 2;
    
    points /= 4;
    
    points %= 3;

    ++ and -- are fine on their own line (count++;). Don't bury them inside bigger expressions — even experienced engineers misread arr[i++] = i;.

    Comparison and logic#

    Java
    score == 200     // equal?            (TWO equals signs. One = means "assign")
    score != 200     // not equal?
    score > 150   score >= 150   score < 150   score <= 150
    
    onTime && score >= 150    // AND: both must be true
    onTime || score >= 150    // OR:  at least one true
    !onTime                   // NOT: flips true/false

    Short-circuit evaluation: && stops as soon as the left side is false (the answer can't be true anymore); || stops as soon as the left side is true. This is used deliberately to avoid errors:

    Java
    int n = 0;
    
    if (n != 0 && 10 / n > 1) System.out.println("never");
    else System.out.println("short-circuit saved us");
    // short-circuit saved us     ← 10 / n (division by zero!) was never evaluated

    In DSA you'll write this pattern all the time: if (i < arr.length && arr[i] == target) — the bounds check must come first.

    Characters are numbers#

    A char stores a Unicode number (How Computers Work Ch 4.3), so arithmetic works on it:

    Java
    System.out.println('a' + 1); // 98     ← 'a' is 97; char + int = int
    
    System.out.println((char) ('a' + 1)); // b      ← cast back to char
    
    System.out.println('d' - 'a'); // 3      ← position of 'd' in the alphabet (0-based)
    
    char grade = 'B';
    
    grade++;
    
    System.out.println(grade); // C

    c - 'a' is one of the most common DSA tricks: it turns letters a..z into array positions 0..25, e.g. for counting letter frequencies with an int[26] (Ch 8, and Arrays and Hashing (coming soon)).

    Casting — converting between types#

    • Widening (small type → big type) happens automatically and is always safe: int → long → double.

      Java
      long big = 200; // int widened to long automatically
      
      double d = 200; // 200.0
    • Narrowing (big → small) needs an explicit cast (type), because information can be lost:

      Java
      System.out.println((int) 3.99); // 3     ← decimals are chopped, not rounded
      
      System.out.println((int) -3.99); // -3    ← toward zero
      
      System.out.println((byte) 200); // -56   ← 200 doesn't fit in a byte; the bits wrap (two's complement)
    • Rounding properly: Math.round(2.5) → 3, and Math.round(-2.5) → -2 (it rounds half up, toward positive infinity).

    Average done right:

    Java
    int total = 649,
        count = 4;
    
    double avg = (double) total / count; // cast FIRST, so the division is done in double → 162.25
    
    double wrong = (double) (total / count); // 162.0 — the int division already threw the fraction away

    Useful Math methods#

    Java
    Math.max(a, b)   Math.min(a, b)   Math.abs(-5)      // 5
    Math.pow(2, 10)                                     // 1024.0  ← returns a double!
    Math.sqrt(49)                                       // 7.0
    Math.floorMod(-7, 3)                                // 2
    Math.addExact(a, b)                                 // like a + b but THROWS on overflow instead of wrapping

    Operator precedence (the order things happen)#

    Like school maths: *, /, % before +, -; comparisons after arithmetic; && before ||; assignment last. When in doubt, add parentheses — they cost nothing and make the code obvious.

    Java
    System.out.println(1 + 2 + "3" + 4 + 5); // 3345  ← left to right: 1+2=3, then "3"+"3"="33", then "334", "3345"

    Gotchas

    • = vs ==: if (score = 200) is a compile error in Java (good!) because the result isn't a boolean.

    • Integer division silently drops fractions.

    • Math.pow returns a double. For integer powers in DSA, multiply in a loop or cast carefully — doubles lose precision above 2⁵³.

    • 10 == 10.0 is true: the int is widened to double before comparing.

    Check yourself

    5 questions
    1

    What do 9 / 4, 9 % 4, 9.0 / 4 and -9 % 4 print?

    Show answer

    2, 1, 2.25, -1.

    2

    After int i = 3; int x = i++ + ++i;, what are x and i? (Work it out step by step.)

    Show answer

    i++ gives 3 (i becomes 4); ++i makes i 5 and gives 5; so x = 3 + 5 = 8, i = 5. (This is exactly why you shouldn't write code like this.)

    3

    Why does if (i < arr.length && arr[i] > 0) never crash, while swapping the two sides can?

    Show answer

    && short-circuits: if i is out of bounds, the left side is false and arr[i] is never evaluated. Swapped, arr[i] runs first and can throw an exception.

    4

    What does 'z' - 'a' evaluate to, and why is that useful?

    Show answer

    25 — it maps letters to indexes 0–25, e.g. for letter-count arrays.

    5

    int total = 7, count = 2; — write the average as a double correctly.

    Show answer

    double avg = (double) total / count; → 3.5.