Skip to content
LumenaryAcademy
Foundations 55 min

Types, operators and control flow

Java's eight primitive types, the arithmetic traps every professional knows, and the statements and expressions that decide and repeat.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Types are promises the compiler checks

In Java every variable, parameter and expression has a type that the compiler knows before the program runs. When you write int age = 42; you are making a promise: age will always hold a 32-bit whole number. The compiler holds you to it. Try age = "forty-two"; and the program will not compile.

That strictness costs a few keystrokes and pays for itself many times over. A misspelled method, a string passed where a number was expected, a value that might be missing: in a dynamically typed language these surface as crashes in production, sometimes months later. In Java most of them surface as red underlines in your editor. Types are also documentation that cannot go out of date; a method declared double average(int[] scores) tells you what it needs and what it gives back.

But types in Java also carry machine-level meaning. An int is not "a whole number" in the mathematical sense; it is exactly 32 bits, and arithmetic on it wraps around when it overflows. A double is a binary fraction, so 0.1 cannot be stored exactly. Professionals know these edges by heart, because the bugs they cause are quiet: no crash, just a wrong number. This lesson walks through them with real output, then turns to the statements that make decisions and repeat work.

DefinitionsH

Primitive types and reference types

Java has exactly eight primitive types. Their sizes are fixed by the language specification and are the same on every computer, unlike C, where an int may vary by platform.

TypeSizeRange or meaningLiteral examples
byte8 bits−128 to 127(byte) 7
short16 bits−32,768 to 32,767(short) 300
int32 bitsabout ±2.1 billion42, 1_000_000, 0xFF, 0b1010
long64 bitsabout ±9.2 × 10¹⁸3_000_000_000L
float32 bitsIEEE 754 binary floating point, about 7 significant digits2.5f
double64 bitsIEEE 754, about 15–16 significant digits2.5, 6.02e23
char16 bitsone UTF-16 code unit, 0 to 65,535'A', 'ñ', '\n'
boolean—true or falsetrue

In practice you will use int, long, double and boolean almost all the time. byte appears when handling raw binary data, and float in graphics and machine-learning code where memory matters more than precision. Underscores in numeric literals are allowed anywhere between digits, purely for readability.

Every other type is a reference type: classes such as String, arrays such as int[], interfaces, records and enums. A variable of a reference type does not hold the object itself; it holds a reference to an object that lives on the heap, or the special value null, meaning "no object". That difference explains a great deal of Java's behaviour, and we return to it in Methods, classes and objects.

Each primitive type has a matching wrapper class (Integer, Long, Double, Character, Boolean and so on) for the places where an object is required, such as inside collections. Java converts between them automatically (autoboxing and unboxing), which is convenient and occasionally surprising.

Definition— var (local-variable type inference)

Since JDK 10 you may write var instead of the type when declaring a local variable with an initial value: var names = new ArrayList<String>();. The variable still has a fixed static type, inferred by the compiler from the right-hand side; var is not dynamic typing. It is allowed only for local variables (and loop variables), never for fields, parameters or return types.

Use var when the type is obvious from the right-hand side or unimportant to the reader, and spell the type out when it carries information. var connection = pool.borrow(); hides something worth knowing; var reader = new BufferedReader(...) hides nothing.

Worked examplesH

Arithmetic and its traps

Run this compact source file and compare each line with what you expected:

java
void main() {
    // Integer arithmetic
    IO.println("7 / 2       = " + (7 / 2));
    IO.println("-7 / 2      = " + (-7 / 2));
    IO.println("-7 % 2      = " + (-7 % 2));
    IO.println("floorMod    = " + Math.floorMod(-7, 2));
    IO.println("7.0 / 2     = " + (7.0 / 2));

    // Overflow wraps around silently
    int big = Integer.MAX_VALUE;
    IO.println("MAX_VALUE   = " + big);
    IO.println("MAX + 1     = " + (big + 1));
    long wide = big + 1L;
    IO.println("as long     = " + wide);

    // Floating point is binary
    IO.println("0.1 + 0.2   = " + (0.1 + 0.2));

    // Casts
    IO.println("(int) 3.99  = " + (int) 3.99);
    IO.println("(int) -3.99 = " + (int) -3.99);
    IO.println("(byte) 200  = " + (byte) 200);
    IO.println("'A' + 1     = " + ('A' + 1));
    IO.println("(char)      = " + (char) ('A' + 1));
    IO.println("1_000_000   = " + 1_000_000);
}
text
7 / 2       = 3
-7 / 2      = -3
-7 % 2      = -1
floorMod    = 1
7.0 / 2     = 3.5
MAX_VALUE   = 2147483647
MAX + 1     = -2147483648
as long     = 2147483648
0.1 + 0.2   = 0.30000000000000004
(int) 3.99  = 3
(int) -3.99 = -3
(byte) 200  = -56
'A' + 1     = 66
(char)      = B
1_000_000   = 1000000

Line by line, the rules behind it:

  • Integer division truncates toward zero. 7 / 2 is 3 and -7 / 2 is -3, not -4. If either operand is a double, the division is floating-point: 7.0 / 2 is 3.5.
  • The remainder % takes the sign of the left operand, so -7 % 2 is -1. That breaks the common test n % 2 == 1 for "is odd" when n is negative; write n % 2 != 0 instead. When you want the mathematical modulus that is never negative for a positive divisor (for example, wrapping around a circular buffer or a clock), use Math.floorMod.
  • Overflow wraps. int arithmetic is arithmetic modulo 2³², using two's complement, so one more than the largest int is the smallest. No exception, no warning. Adding 1L, a long literal, makes the whole expression long and the answer is correct.
  • Floating point is binary. 0.1 has no exact binary representation, just as 1/3 has no exact decimal one, so tiny errors appear. Never compare doubles with == after arithmetic; compare with a tolerance, or use a different type.
  • Casts from floating point truncate toward zero, and narrowing casts between integer types keep only the low bits: 200 does not fit in a byte, and its low eight bits mean −56.
  • char is a number. 'A' + 1 promotes the char to int and gives 66; casting back gives 'B'.

Java applies binary numeric promotion before every arithmetic operator: if either operand is double, both become double; otherwise if either is float, both become float; otherwise if either is long, both become long; otherwise both become int, even if they were byte, short or char. That last rule is why this does not compile:

java
short s = 10;
s = s + 1;   // error: incompatible types: possible lossy conversion from int to short

s + 1 is an int, and Java will not silently squeeze an int into a short. Curiously, s += 1; does compile, because compound assignment operators include an implicit cast back to the variable's type. It is one of the language's small inconsistencies, kept for compatibility.

ComputationC

Money, overflow and exactness

Two professional rules follow from the traps above. First, never use double for money. Second, when overflow would be a bug, ask Java to detect it.

java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] args) {
        // Ten coffees at 0.10 each, added up with double
        double total = 0;
        for (int i = 0; i < 10; i++) {
            total += 0.10;
        }
        System.out.println("double total:     " + total);
        System.out.println("equals 1.0?       " + (total == 1.0));

        // The same with BigDecimal, built from strings
        BigDecimal exact = BigDecimal.ZERO;
        BigDecimal price = new BigDecimal("0.10");
        for (int i = 0; i < 10; i++) {
            exact = exact.add(price);
        }
        System.out.println("BigDecimal total: " + exact);

        // Split 100.00 three ways, rounding to cents
        BigDecimal share = new BigDecimal("100.00").divide(new BigDecimal(3), 2, RoundingMode.HALF_EVEN);
        System.out.println("one share:        " + share);

        // Overflow that is detected instead of silent
        var seconds = 3_000_000_000L;           // var infers long from the L suffix
        try {
            int asInt = Math.toIntExact(seconds);
            System.out.println(asInt);
        } catch (ArithmeticException e) {
            System.out.println("toIntExact failed: " + e.getMessage());
        }
    }
}
text
double total:     0.9999999999999999
equals 1.0?       false
BigDecimal total: 1.00
one share:        33.33
toIntExact failed: integer overflow

BigDecimal stores a decimal number exactly, as an arbitrary-precision integer and a scale (the number of digits after the point). Three habits matter:

  1. Build it from a string, new BigDecimal("0.10"), not from a double. new BigDecimal(0.10) faithfully records the binary error already in the double.
  2. BigDecimal objects are immutable: exact.add(price) returns a new value and leaves exact unchanged, so you must assign the result. Forgetting exact = is a classic bug.
  3. Division must say how to round when the result does not terminate. HALF_EVEN ("banker's rounding") is common in finance because it does not drift upward over many operations. Where the remaining cent goes when 100.00 is split three ways is a business decision, not a programming one.

Many systems store money as a long count of the smallest unit (cents, paise, yen) instead. That is fast and exact, as long as you remember which currency has how many decimal places.

The Math class has exact variants of the risky operations: Math.addExact, subtractExact, multiplyExact, toIntExact and others throw an ArithmeticException instead of wrapping. The try/catch you see above catches that exception; exceptions get a lesson of their own in Exceptions, equality and immutability.

ExplanationH

A first look at strings

String is a class, not a primitive, but Java gives it special support: literals in double quotes, + for joining, and switch on strings. Strings are immutable: every method that seems to change a string, such as toUpperCase() or replace(...), returns a new one.

java
String city = "Kraków";
city.length()              // 6
city.toUpperCase()         // "KRAKÓW"
city.charAt(0)             // 'K'
city.contains("kó")        // true
city.substring(0, 3)       // "Kra" (from index 0 up to, not including, 3)
"a,b,,c".split(",")        // ["a", "b", "", "c"]
"  padded  ".strip()       // "padded"
String.join("-", "2026", "11", "19")   // "2026-11-19"

Text blocks (JDK 15) are string literals that span lines. They begin with three quotes and a line break; the compiler removes the indentation common to all lines, so the text can be indented with your code. They are ideal for JSON, SQL and messages, and pair well with formatted(...), which fills in %d, %s and the other placeholders of printf. You will see one in the next program.

One rule now, explained fully later: compare strings with equals, not ==. == on references asks "is this the same object?", while equals asks "do these contain the same characters?". Two strings with the same text can be different objects.

Worked examplesH

Decisions: if, the conditional operator and switch

if and else work as in most languages; the condition must be a boolean (Java will not treat 0 or null as false). The conditional operator condition ? a : b is an expression that picks one of two values, handy for short choices.

switch has two forms. The old form, inherited from C, uses case 1: labels and falls through from one case to the next unless you write break. The modern form (JDK 14) uses arrow labels, never falls through, may list several constants per case, and can be used as an expression that produces a value. A switch expression must be exhaustive: it must handle every possible input, usually with a default. When a case needs several statements, put them in a block and give the result with yield.

java
public class Main {
    static boolean isLeap(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }

    static int daysIn(int month, int year) {
        return switch (month) {
            case 4, 6, 9, 11 -> 30;
            case 2 -> isLeap(year) ? 29 : 28;
            case 1, 3, 5, 7, 8, 10, 12 -> 31;
            default -> throw new IllegalArgumentException("no month " + month);
        };
    }

    static String season(String monthName) {
        // Southern-hemisphere seasons, as in Sydney or Santiago
        return switch (monthName) {
            case "December", "January", "February" -> "summer";
            case "March", "April", "May" -> "autumn";
            case "June", "July", "August" -> "winter";
            default -> {
                String lower = monthName.toLowerCase();
                yield lower.startsWith("s") || lower.startsWith("o") || lower.startsWith("n") ? "spring" : "unknown";
            }
        };
    }

    public static void main(String[] args) {
        for (int year : new int[] {1900, 2000, 2024, 2026}) {
            System.out.println(year + (isLeap(year) ? " is" : " is not") + " a leap year");
        }

        int total = 0;
        for (int m = 1; m <= 12; m++) {
            total += daysIn(m, 2028);
        }
        System.out.println("Days in 2028: " + total);
        System.out.println("July in Santiago: " + season("July"));
        System.out.println("October in Sydney: " + season("October"));

        String report = """
                Month report
                  months checked: %d
                  shortest:       %d days
                """.formatted(12, daysIn(2, 2026));
        System.out.print(report);
    }
}
text
1900 is not a leap year
2000 is a leap year
2024 is a leap year
2026 is not a leap year
Days in 2028: 366
July in Santiago: winter
October in Sydney: spring
Month report
  months checked: 12
  shortest:       28 days

Some details worth noticing:

  • && and || short-circuit: in isLeap, if year % 4 == 0 is false, the rest of the && is never evaluated. You can rely on this to guard a later test, as in s != null && s.isEmpty().
  • A default arm may throw instead of producing a value. That is the honest answer for an impossible month, and much better than returning a made-up number such as 0.
  • The text block's closing quotes sit on their own line, so the string ends with a newline; that is why the program uses print, not println, for it.
  • switch works on int and the smaller integer types, char, String and enums, and since JDK 21 on any type through patterns, which you will meet in Records, sealed types and pattern matching.
Worked examplesH

Loops: for, while, do-while, break and continue

Java has four loops. The classic for (for (init; condition; update)) is for counting. The enhanced for (for (String city : cities)) visits every element of an array or collection and is what you should reach for first, because it cannot go out of bounds. while tests its condition before each pass; do/while tests after, so its body always runs at least once. break leaves a loop, continue skips to the next pass, and a label lets break or continue act on an outer loop.

java
void main() {
    // while: how many steps does the Collatz rule take to reach 1?
    long n = 27;
    int steps = 0;
    while (n != 1) {
        n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
        steps++;
    }
    IO.println("27 reaches 1 after " + steps + " steps");

    // do-while: the body runs at least once
    int digits = 0;
    int value = 0;
    do {
        digits++;
        value /= 10;
    } while (value != 0);
    IO.println("0 has " + digits + " digit");

    // continue skips to the next pass; a labelled break leaves both loops
    char[][] seats = {
        {'x', '.', 'x', 'x', '.'},
        {'x', 'x', 'x', '.', 'x'},
        {'.', 'x', '.', '.', 'x'},
        {'.', '.', '.', '.', '.'},
    };
    int foundRow = -1, foundSeat = -1;
    search:
    for (int row = 0; row < seats.length; row++) {
        for (int s = 0; s + 1 < seats[row].length; s++) {
            if (seats[row][s] == 'x') {
                continue;
            }
            if (seats[row][s + 1] == '.') {
                foundRow = row;
                foundSeat = s;
                break search;
            }
        }
    }
    IO.println("Two seats together: row " + foundRow + ", seats " + foundSeat + " and " + (foundSeat + 1));
}
text
27 reaches 1 after 111 steps
0 has 1 digit
Two seats together: row 2, seats 2 and 3

The Collatz loop uses a long because the sequence starting at 27 climbs into the thousands before falling, and for larger starting values it can exceed the int range; choosing the wider type up front is cheaper than debugging an overflow later. The digit counter shows why do/while exists: the number 0 has one digit, and a plain while (value != 0) loop would have counted none. The seat search uses a two-dimensional array (an array of arrays) and a labelled break search; to stop both loops at the first match. Without the label, break would leave only the inner loop and the search would carry on to row 3.

Labelled breaks are legitimate but uncommon in professional code; when you find yourself reaching for one, consider moving the search into its own method and using return, which is usually clearer.

Common misconceptionsH

Common mistakes

Misconception

"average = sum / count gives the average." If both are int, the division truncates before the result is stored, even when average is a double. Convert first: (double) sum / count.

Misconception

"An int can hold any whole number I am likely to need." Milliseconds since 1970, file sizes, world population, and the product of two "small" numbers such as 1,000,000 × 1,000,000 all exceed it. Use long, and the Math.*Exact methods where overflow would be a bug.

Misconception

"Old-style switch stops after the matching case." With colon labels, execution falls through into the following cases until a break. Prefer arrow labels, which never fall through.

Misconception

"var makes Java dynamically typed." A var variable's type is fixed at compile time. var count = 0; count = "zero"; is a compile error, exactly as if you had written int.

Exercises

Exercises

Every program in these exercises was run on JDK 25; predict the output before you check.

1. Types, operators and control flow

Warm-upComputational

What does this program print?

void main() {
    IO.println(17 / 5 + 17 % 5);
}

2. Types, operators and control flow

CoreComputational

What does this program print?

void main() {
    char c = 'a';
    c += 2;
    IO.println(c);
}

3. Types, operators and control flow

CoreComputational

This uses the old colon form of switch. What does it print?

void main() {
    int count = 0;
    int day = 2;
    switch (day) {
        case 1: count += 1;
        case 2: count += 10;
        case 3: count += 100;
            break;
        default: count += 1000;
    }
    IO.println(count);
}

4. Types, operators and control flow

StretchComputational

What does this program print? (1,000,000² = 10¹², and 2³² = 4,294,967,296.)

void main() {
    int x = 1_000_000;
    IO.println(x * x);
}

5. Types, operators and control flow

CoreComputational

What does this program print?

void main() {
    IO.println(5 / 2 * 2.0);
}

6. Types, operators and control flow

CoreHuman

What happens when you run this?

void main() {
    short s = 10;
    s = s + 1;
    IO.println(s);
}
Choose one

7. Types, operators and control flow

Warm-upHuman

You are storing prices such as 19.99 in an online shop's order system. Which choices are sound? Choose all that apply.

Choose all that apply

Further reading and resources