dev only

Expressions & Output

Printing Output

Two ways to print in Java:

  • System.out.println(value) — prints, then moves to a new line.
  • System.out.print(value) — prints, and stays on the same line.
System.out.print("Score: ");
System.out.println(24);
// Output: Score: 24

Math Expressions

+ - * / work the same way you'd expect, with one big exception: dividing two whole numbers throws away the decimal part.

System.out.println(7 / 2); // prints 3, not 3.5

This is called truncating division, and it's the single most common source of "wrong answer, no error message" bugs you'll run into. If you want the decimal part, at least one of the two numbers needs to be a double:

System.out.println(7.0 / 2); // prints 3.5

Order of Operations

Same rules as math class: * and / happen before + and -. Parentheses override that.

System.out.println(2 + 3 * 2);   // 8
System.out.println((2 + 3) * 2); // 10

The Remainder Operator (%)

% gives you what's left over after dividing. 5 % 2 is 1, because 2 fits into 5 twice, with 1 left over.

int totalSeconds = 150;
System.out.println(totalSeconds / 60); // 2 — whole minutes
System.out.println(totalSeconds % 60); // 30 — leftover seconds
// 150 seconds = 2 minutes, 30 seconds

Common Pitfalls

  • Dividing two whole numbers and expecting a decimal. It truncates instead — check whether at least one side is a double.
  • Dividing by zero. Whole-number division by 0 crashes the program. Decimal division by 0.0 doesn't crash, but gives a nonsense result (Infinity or NaN) — a sign something's wrong upstream.

Key Takeaways

  • print stays on the line; println moves to a new one.
  • Dividing two whole numbers truncates the decimal part instead of rounding.
  • Use *// before +/-, unless parentheses say otherwise.
  • % gives the remainder after division — useful for splitting a total into two units (like seconds into minutes and seconds).

Derived from csawesome-2026: unit-1-using-objects-and-methods/1.03-expressions-and-output.md (CSA 1.3)