Operators and precedence

Java has the operator set of C with two changes that matter: a boolean expression is the only thing an if accepts, and the condition operators do not turn a number into a truth value. The rest is arithmetic, comparison, bit manipulation and the assignment forms that combine an operation with a store.

Arithmetic and comparison

+ - * / % work on numbers, and + also joins a string to anything on its right. == != < <= > >= compare two values and give a boolean; for two objects, == compares references, not contents, which is the subject of lesson 012.

The file Operators.java runs every operator once and labels the result:

public class Operators { public static void main(String[] args) { int a = 17; int b = 5; System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); int total = 10; total += 5; System.out.println("total = " + total); total *= 2; System.out.println("total = " + total); System.out.println("a > b = " + (a > b)); System.out.println("a == b = " + (a == b)); int calls = 0; boolean shortCircuit = false && count(calls++); System.out.println("false && call: " + shortCircuit + ", calls: " + calls); boolean evaluated = true && count(calls++); System.out.println("true && call: " + evaluated + ", calls: " + calls); int flags = 0b1010; System.out.println("flags & 0b0110 = " + (flags & 0b0110)); System.out.println("flags | 0b0110 = " + (flags | 0b0110)); System.out.println("flags ^ 0b0110 = " + (flags ^ 0b0110)); System.out.println("1 << 4 = " + (1 << 4)); System.out.println("-16 >> 2 = " + (-16 >> 2)); System.out.println("-16 >>> 2 = " + (-16 >>> 2)); int result = 2 + 3 * 4; int grouped = (2 + 3) * 4; System.out.println("2 + 3 * 4 = " + result); System.out.println("(2 + 3) * 4 = " + grouped); } static boolean count(int value) { System.out.println("count called with " + value); return true; } }

javac -Xlint:all Operators.java
java Operators

a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
total = 15
total = 30
a > b = true
a == b = false
false && call: false, calls: 0
count called with 0
true && call: true, calls: 1
flags & 0b0110 = 2
flags | 0b0110 = 14
flags ^ 0b0110 = 12
1 << 4 = 16
-16 >> 2 = -4
-16 >>> 2 = 1073741820
2 + 3 * 4 = 14
(2 + 3) * 4 = 20

Compound assignment

x += y stores the sum back into x, and the same pattern works with every arithmetic and bitwise operator. i++ adds one and gives the old value, ++i adds one and gives the new one; when the value of the expression is not used, the two are the same.

public class Compound { public static void main(String[] args) { int total = 10; total += 5; System.out.println("+=: " + total); total *= 2; System.out.println("*=: " + total); total -= 3; System.out.println("-=: " + total); total /= 4; System.out.println("/=: " + total); int i = 5; System.out.println("i++: " + (i++)); System.out.println("i: " + i); System.out.println("++i: " + (++i)); } }

javac -Xlint:all Compound.java
java Compound

+=: 15
*=: 30
-=: 27
/=: 6
i++: 5
i: 6
++i: 7

i++ prints 5 and leaves 6, ++i prints the value after the addition. A compound assignment also casts back to the type of the left side, which is why byte b = 1; b += 1; compiles while b = b + 1; does not.

Short-circuit logic

&& evaluates its right side only when the left is true, and || only when the left is false. The rule is not an optimisation: a program relies on it to guard a null check or an index, as in list != null && list.size() > 0. The program counts the calls to show which side ran.

public class Logic { public static void main(String[] args) { int calls = 0; boolean result = false && check(calls++); System.out.println("false && check: " + result + ", calls: " + calls); result = true || check(calls++); System.out.println("true || check: " + result + ", calls: " + calls); result = true && check(calls++); System.out.println("true && check: " + result + ", calls: " + calls); } static boolean check(int value) { System.out.println("check(" + value + ")"); return true; } }

javac -Xlint:all Logic.java
java Logic

false && check: false, calls: 0
true || check: true, calls: 0
check(0)
true && check: true, calls: 1

The first two lines show no call: the left side already decided. The third line calls check and increments the counter, so calls is 1 at the end. The non-short-circuit forms are & and |, which always evaluate both sides; they are for bit masks, not for conditions.

Bitwise operators and shifts

The six bitwise operators work on the bits of an integer. & is and, | is or, ^ is exclusive or, and ~ flips every bit. The shifts move the bits left or right: << fills with zeros on the right, >> keeps the sign bit and >>> fills with zeros on the left.

The numbers are in the output of the first program: 0b1010 and 0b0110 have a single common bit, so the and gives 2, the or gives 14 and the exclusive or gives 12. 1 << 4 is 16, the same as 2 to the 4th, and a negative number shifted with >>> becomes the large positive value 1073741820 because the sign bit is filled with zero.

Precedence

Multiplication and the remainder bind tighter than addition, addition binds tighter than the shifts, and the shifts bind tighter than comparison. A reader should not have to remember that, so a mixed expression gets parentheses, and the program shows the two readings that differ:

public class Precedence { public static void main(String[] args) { System.out.println("2 + 3 * 4 = " + (2 + 3 * 4)); System.out.println("(2 + 3) * 4 = " + ((2 + 3) * 4)); System.out.println("1 + 2 << 3 = " + (1 + 2 << 3)); System.out.println("1 + (2 << 3) = " + (1 + (2 << 3))); System.out.println("-16 >> 2 = " + (-16 >> 2)); System.out.println("-16 >>> 2 = " + (-16 >>> 2)); } }

javac -Xlint:all Precedence.java
java Precedence

2 + 3 * 4 = 14
(2 + 3) * 4 = 20
1 + 2 << 3 = 24
1 + (2 << 3) = 17
-16 >> 2 = -4
-16 >>> 2 = 1073741820

1 + 2 << 3 is (1 + 2) << 3 because addition binds tighter, and the result is 24; the parentheses in the second line change it to 17. Both lines compile, and only one of them says what a reader expects, which is the argument for the parentheses.

A random number

A die roll is arithmetic with a boundary case: nextInt(6) returns 0 to 5, so the + 1 moves it to 1 to 6. The generator is seeded with 42 here so that the output is the same on every run; a program that wants a different sequence leaves the seed out.

import java.util.Random; public class Roll { public static void main(String[] args) { Random random = new Random(42); int total = 0; for (int i = 0; i < 5; i++) { int roll = random.nextInt(6) + 1; total += roll; System.out.println("roll " + (i + 1) + ": " + roll); } System.out.println("total: " + total); System.out.println("average: " + (total / 5.0)); } }

javac -Xlint:all Roll.java
java Roll

roll 1: 3
roll 2: 4
roll 3: 1
roll 4: 3
roll 5: 1
total: 12
average: 2.4

total / 5.0 is a floating-point division because of the 5.0, and the average has the fraction that total / 5 would discard. The random page has the same generator with a seed from the clock.

Exercises

  1. Predict the value of 17 % 5 + 2 * 3, then check it in jshell.
  2. Change false && check(calls++) in Logic.java to false & check(calls++) and run it again. Which line appears, and why?
  3. Write the bit pattern of 0b1010 and 0b0110 on paper and confirm the three results of the and, the or and the exclusive or.
  4. Give Roll.java no seed and run it twice. Are the five rolls the same?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is 2 + 3 * 4?

    Answer

    14

    Multiplication binds tighter than addition, so the expression is 2 + 12.

  2. What is (2 + 3) * 4?

    Answer

    20

    The parentheses add first, and 5 times 4 is 20.

  3. What does && do when its left side is false?

    Answer

    It skips the right side and gives false

    The and operator short-circuits: a false left side decides the result.

  4. What does this program print? public class Q1 { public static void main(String[] args) { int calls = 0; boolean result = false && check(calls++); System.out.println(result + " " + calls); } static boolean check(int value) { return true; } }

    Answer

    false 0

    The right side of a false && is never evaluated, so the increment does not happen.

  5. What is 1 << 4?

    Answer

    16

    A left shift by four multiplies by two four times, so 1 becomes 16.

  6. What does -16 >> 2 give?

    Answer

    -4

    The signed shift keeps the sign bit, and -16 divided by 4 is -4.

  7. What does this program print? public class Q2 { public static void main(String[] args) { int i = 5; System.out.println(i++); System.out.println(i); } }

    Answer

    5 / 6

    The postfix increment gives the old value and leaves the variable at 6.

  8. What does this program print? public class Q3 { public static void main(String[] args) { int total = 10; total *= 2; total -= 3; System.out.println(total); } }

    Answer

    17

    The multiplication gives 20 and the subtraction gives 17.

  9. What is the first line of the compiler output for this program? public class Q4 { public static void main(String[] args) { int x = 0; if (x = 1) { System.out.println(x); } } }

    Answer

    error: incompatible types: int cannot be converted to boolean

    An if condition must be a boolean, and the assignment of an int is not one; Java does not treat 1 as true.

  10. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println(0b1010 & 0b0110); } }

    Answer

    2

    The only bit set in both numbers is the 2 bit, so the and gives 2.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev