Predict the output · Java
Operators, conditions and loops
Increment operators, precedence, short-circuiting and loop counts.
Learn: Predicting Java operators, conditions and loops7 minute read
Operator puzzles are short programs full of ++, && and loops, and the question is always the same: what does it print? Interviewers like them because they reward careful tracing, which is the same skill you use to debug a failing test. Java defines the order of evaluation exactly, so every such snippet has one correct answer. These rules are enough to find it.
Rule 1: i++ gives the old value, ++i the new one
Both forms add 1 to the variable. The difference is the value the expression gives back. i++ (post-increment) gives the value before the increment. ++i (pre-increment) gives the value after it. In a = i++, a gets the old value.
The trap i = i++ runs in three steps: save the old value, increment i, then assign the saved old value back. The increment is overwritten, so i does not change.
Rule 2: operands are evaluated left to right
An operand is a value that an operator works on, such as i in i + 1. Java always evaluates the left operand fully before the right one, including any side effects. A side effect is a change that an expression makes besides giving a value, such as an increment. So in i++ + i, the left part gives the old value and leaves i incremented, and the right part then reads the new value. In C (another programming language) this kind of expression has no defined answer; in Java it does.
public class Main {
public static void main(String[] args) {
int i = 3;
int a = i++ + i;
System.out.println(a + " " + i);
int j = 3;
j = j++;
System.out.println(j);
}
}
7 4 3
Rule 3: precedence, then left to right
Precedence decides which operator is applied first. From high to low, the common ones are: unary operators (operators with one operand, like ! and -x) and casts, then * / %, then + -, then comparisons, then == !=, then &&, then ||, then ?: (the conditional operator: cond ? a : b gives a when cond is true and b otherwise), and assignment last. Operators on the same level group from left to right, so 10 - 4 - 3 is 3 and 20 / 2 * 5 is 50. Assignment, ?: and the unary operators are the exceptions and group from right to left.
Rule 4: && and || can skip the right side
&& stops when the left side is false, and || stops when the left side is true, because the answer is already known. This is called short-circuiting. Anything on the right, such as ++x or a method call, then never runs. The single-character forms & and | on booleans (true or false values) always evaluate both sides.
Rule 5: compound assignment hides a cast
A compound assignment is an operator such as += that calculates and assigns in one step. x += y means x = (type of x) (x + y). So int x = 7; x /= 2.0; compiles and leaves 3, because 3.5 is cast back to int (a cast converts a value to another type). The long form x = x / 2.0 would not compile: Java refuses to build the program, because a double cannot go into an int without a cast you write yourself.
public class Main {
public static void main(String[] args) {
int calls = 0;
boolean r = true || (++calls > 0);
System.out.println(r + " " + calls);
int x = 7;
x /= 2.0;
System.out.println(x);
for (int k = 0; k < 10; k += 4) {
System.out.print(k + " ");
}
System.out.println();
}
}
true 0 3 0 4 8
Rule 6: a classic switch falls through
A switch statement with case 1: labels jumps to the matching case and then runs every statement below it until a break. Missing breaks make later cases run too. The arrow form, case 1 -> ..., never falls through.
public class Main {
public static void main(String[] args) {
int level = 1;
switch (level) {
case 1:
System.out.println("one");
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
}
}
}
one two
Rule 7: ?: has one type for both branches
When both branches of ?: are numbers (here an int and a double, a number with a fraction), Java gives the result one shared type. So true ? 1 : 2.0 is the double 1.0, even though the 2.0 branch never runs.
Tracing loops
Write a small table: the value of each variable when the condition is checked, and what the body prints. The update part of a for loop runs after the body. continue skips the rest of one pass; break ends the loop. A post-decrement in a condition, as in while (n-- > 0), compares the old value, but the body already sees the new one, and the variable is decremented one last time when the check fails. For example, with n = 2: the check sees 2, the body sees 1; the check sees 1, the body sees 0; the check sees 0 and fails, and n ends at -1.
How to answer in an interview
Trace out loud and keep a running value for each variable. "a starts at 5. a++ gives 5 and a becomes 6. ++a makes it 7 and gives 7. So r is 12." Then add one sentence on real code: you would split such an expression into separate lines so nobody has to trace it.
Common mistakes
- Mixing up the value of
i++with the value ofiafterwards. - Assuming the right side of
&&or||always runs. - Grouping
10 - 4 - 3from the right. - Forgetting the hidden cast in
+=. - Stopping a classic switch at the next
caselabel.
Recap
Track old and new values for every ++ and --. Evaluate from the left, apply precedence, and check whether short-circuiting skips the right side. Remember the cast in compound assignment and the fall-through of a classic switch.
10 questions0/10 solved
| Status | Question | Difficulty | Asked in |
|---|---|---|---|
| Not started | i++ versus ++i | Easy | Asked in: Infosys, PhonePe, Wipro |
| Not started | A loop with continue and break | Easy | |
| Pro+ | Operator precedence and left-to-right order | Easy-Medium | |
| Pro+ | || versus | with a side effect | Medium | |
| Pro+ | i = i++ | Medium | |
| Pro+ | Compound assignment hides a cast | Medium | |
| Pro+ | switch without break | Medium | |
| Pro+ | while (n-- > 0) | Medium | |
| Pro+ | a++ + ++a in one expression | Medium-Hard | |
| Pro+ | A ternary that mixes int and double | Hard |
The first 2 questions of each topic are free. Pro+ opens every question.