Adding one to the largest int — Aptitude Question
Adding one to the largest int: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 75 seconds
Question
What does this Java program print?
public class Main {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE + 1);
}
}Options
- 2147483647
- 2147483648
- -2147483648
- The program does not compile
Show the answer and the worked solution
Correct answer: C. -2147483648
Worked solution
- Integer.MAX_VALUE is 2147483647 and the literal 1 is an int, so the addition is performed in 32-bit int arithmetic.
- Java specifies wrap-around on overflow rather than an exception, so the result rolls over to the most negative int.
- That value is -2147483648, which is what gets printed.
Answer: -2147483648.
The idea
Java int arithmetic is modulo 2 to the power 32 and never reports overflow. Casting one operand to long, or using Math.addExact, is how you avoid the silent wrap.
Shortcut. 32-bit two's complement wraps round: MAX_VALUE + 1 is MIN_VALUE, −2³¹ = −2147483648.
Common trap. 2147483648 does the sum in ordinary arithmetic; that value does not fit in an int, and Java wraps silently instead of widening.
All Programming Fundamentals questions · placement mock tests