Skip to content
Study Hall
Lesson 3 of 3Programming Basics
Unit 2 · Lesson 3 of 3

Operators, Expressions and Input

How Java evaluates an expression, what + does to Strings, the Math methods worth knowing, and how to read typed input with Scanner without falling into the newline trap.

5 min read12 practice questionsAsk AI about this →

Key things to remember

  1. 1Precedence: brackets, then unary, then * / % left to right, then + - left to right, then assignment.
  2. 2% sits at the same level as * and /, so 10 % 4 * 2 is (10 % 4) * 2 = 4.
  3. 3If either operand of + is a String, + joins: "total: " + 1 + 2 gives total: 12, so bracket the arithmetic.
  4. 4x += 3 means x = x + 3; x++ uses the old value then increments, ++x increments then uses the new one.
  5. 5Math.round returns a long; to round to two decimals use Math.round(v * 100) / 100.0 with a double divisor.
  6. 6After nextInt() or nextDouble(), call a bare nextLine() before reading a line of text.

An expression is anything that produces a value: 3, a + b, Math.sqrt(2). Java evaluates expressions the way you were taught to evaluate arithmetic, with one addition — the modulo operator — and one complication, which is that the same + symbol means two entirely different things depending on what sits on either side of it. Predictable output starts with knowing the order Java works in.

Java evaluates the top of this ladder first, not left to right.( )highest — forces the order++ -- !unary: step, logical NOT* / %multiply, divide, remainder+ -add and subtract< <= > >=relational comparison== !=equal / not equal&&logical AND (short-circuits)||logical OR (short-circuits)= += -= *=lowest — assigns right to leftWhy the order matters3 + 4 * 2= 3 + 8 = 11 (not 14)(3 + 4) * 2= 7 * 2 = 14Integer division surprises7 / 2 is 37 % 2 is 17.0 / 2 is 3.5one double operand → double resultWhen in doubt, add brackets. They cost nothing and they say exactly what you meant.
Fig 1Operator precedence from highest to lowest, with the direction each level is evaluated.
LevelOperatorsDirectionNote
1( )Innermost firstBrackets always win — use them when in doubt
2++ -- unary -Right to leftApplies to a single operand
3* / %Left to right% sits at the same level as multiply and divide
4+ -Left to right+ is also String joining when a String is involved
5= += -= *= /= %=Right to leftAssignment happens last, once the value exists

The part that catches people is level 3. BEDMAS teaches multiplication and division as one level evaluated left to right, and % simply joins that same level. So 10 % 4 * 2 is not 10 % 8; it is (10 % 4) * 2, which is 2 × 2 = 4. In the same way 20 / 3 / 2 is (20 / 3) / 2, which with integer division is 6 / 2 = 3, not 20 / 6.

System.out.println(3 + 4 * 2);         // 11  multiply first
System.out.println((3 + 4) * 2);       // 14  brackets first
System.out.println(10 % 4 * 2);        // 4   (10 % 4) = 2, then 2 * 2
System.out.println(20 / 3 / 2);        // 3   (20 / 3) = 6, then 6 / 2
System.out.println(2 + 3 * 4 - 6 / 2); // 11  2 + 12 - 3
Same-level operators run left to right, which decides three of these five answers.

Compound assignment and increment

ShorthandLong formStarting valueResult
x += 3x = x + 3x is 58
x -= 2x = x - 2x is 86
x *= 4x = x * 4x is 624
x /= 5x = x / 5x is 244 (integer division)
x++x = x + 1x is 45
x--x = x - 1x is 54
int a = 5;
int b = a++;   // b is 5, a is now 6  (post-increment: use, then add)
int c = ++a;   // a becomes 7, c is 7 (pre-increment: add, then use)
System.out.println(a + " " + b + " " + c);   // prints: 7 5 7
Post-increment hands back the old value; pre-increment hands back the new one.
The classic concatenation trap
If either side of + is a String, Java joins instead of adding. Because + runs left to right, "total: " + 1 + 2 prints total: 12 — the String swallows the 1, and the result swallows the 2. Brackets fix it: "total: " + (1 + 2) prints total: 3, because the addition finishes before the String gets involved.
System.out.println("total: " + 1 + 2);    // total: 12
System.out.println("total: " + (1 + 2));  // total: 3
System.out.println(1 + 2 + " is total");  // 3 is total
System.out.println('A' + 1);              // 66 — no String, so char arithmetic
System.out.println("" + 'A' + 1);         // A1 — the empty String forces joining
Left-to-right evaluation decides every one of these, so read the line from the left.

Math methods and keyboard input

MethodWhat it doesReturnsExample
Math.round(x)Rounds a double to the nearest whole number; halves go uplongMath.round(2.5) is 3; Math.round(-2.5) is −2
Math.sqrt(x)Square rootdoubleMath.sqrt(16) is 4.0
Math.pow(a, b)a raised to the power bdoubleMath.pow(2, 10) is 1024.0
Math.abs(x)Absolute valuesame type as the argumentMath.abs(-7) is 7
Math.max(a, b), Math.min(a, b)Larger or smaller of two valuessame type as the argumentsMath.max(3, 9) is 9
Math.random()A random double from 0.0 up to but not including 1.0double(int)(Math.random() * 6) + 1 gives 1 to 6
Rounding to centsScale up, round, scale back downdoubleMath.round(v * 100) / 100.0
Scanner reads what the user types, one token or one line at a time.import java.util.Scanner;at the very top of the fileScanner sc = new Scanner(System.in);build one, usually inside mainint n = sc.nextInt();reads one whole numberdouble d = sc.nextDouble();reads one decimal numberString s = sc.nextLine();reads the rest of the lineThe nextInt-then-nextLine trapThe user types 42, Enter, Ada, Enter:42↵Ada↵nextInt() takes 42 and stopsthe ↵ is still sitting in the bufferso the next nextLine() hits that ↵straight away and returns "".FIX — one of these:sc.nextLine(); // eat itor read every line withnextLine() + Integer.parseInt.nextInt and nextDouble stop at whitespace; nextLine stops at the end of the line.
Fig 2How a Scanner consumes tokens from the typed line, and where the leftover newline sits.

A Scanner reads what the user types. Because it lives in the java.util package rather than the core language, it has to be imported at the very top of the file, above the class. You then create one Scanner attached to System.in and call the method matching the kind of value you want: nextInt() for a whole number, nextDouble() for a decimal, next() for a single word, and nextLine() for a whole line of text.

import java.util.Scanner;

public class Order {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("How many items? ");
        int count = sc.nextInt();

        System.out.print("Price each: ");
        double price = sc.nextDouble();

        sc.nextLine();              // consume the leftover newline
        System.out.print("Your name: ");
        String name = sc.nextLine();

        double total = count * price * 1.13;   // 13% HST
        System.out.println(name + " owes " + Math.round(total * 100) / 100.0);
    }
}
A complete input program. The bare sc.nextLine() on its own line is the fix, not a mistake.
The nextInt then nextLine bug
nextInt reads the digits and stops, leaving the Enter keypress sitting in the input buffer. The next call to nextLine finds that leftover newline immediately, returns an empty String, and never pauses for the user — so a program that asks for a name appears to skip the question entirely. The fix is an extra bare sc.nextLine() after the last number, whose only job is to swallow the newline.

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
Evaluate 7 + 12 / 4 * 2 - 3 % 2 step by step using int arithmetic.
Example 2
Predict the output of System.out.println("Score: " + 8 + 2); and of System.out.println(8 + 2 + " points");, then explain the difference.
Example 3
A program asks for a mark with nextInt, then a name with nextLine. The name prompt appears but the program never stops for an answer. Diagnose and fix it.
Example 4
A price of 24.5678 dollars must be displayed rounded to the nearest cent. Write and justify the expression.

Where marks get lost

  • Expecting "total: " + 1 + 2 to print total: 3. Evaluation is left to right, so it prints total: 12 unless you bracket the sum.
  • Forgetting the bare nextLine() after nextInt(), so the next text prompt is skipped and an empty String is stored.
  • Writing Math.round(v * 100) / 100 with an int divisor, which truncates and throws away the decimals you just rounded to.
  • Assuming % binds more loosely than *. They share a level and run left to right, so 10 % 4 * 2 is 4, not 10 % 8.
  • Forgetting import java.util.Scanner; above the class, or building a new Scanner every time input is read instead of reusing one.

Flashcards 10

Where does % sit in the order of operations?
What does "total: " + 1 + 2 print?
How do you force the addition inside a printed String?
x++ versus ++x
+ 6 more

Practice

1
What does 3 + 4 * 2 evaluate to?
2
Using int arithmetic, what does 20 / 3 / 2 evaluate to?
3
What does 10 % 4 * 2 evaluate to?
4
What exactly does System.out.println("Total: " + 1 + 2); print?
5
int x = 5; then x += 3; then x *= 2;. What is x?
6
int a = 5; int b = a++; What value is stored in b?
7
What does Math.pow(2, 5) evaluate to?
8
What does Math.round(2.5) return?
9
Which expression produces a random whole number from 1 to 10 inclusive?
10
A program calls sc.nextInt() and then sc.nextLine() to read a name, but the name comes back empty. Why?
11
Match each Math call to what it produces.
Math.sqrt(25)
Math.pow(3, 3)
Math.abs(-8)
Math.max(4, 11)
12
Order these steps as Java evaluates 2 + 3 * 4 - 6 / 2.
  1. 1Evaluate 6 / 2, giving 3
  2. 2Subtract 3 from 14, giving 11
  3. 3Add 2 + 12, giving 14
  4. 4Evaluate 3 * 4, giving 12

Spot a mistake on this page? Let us know