AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumjavaoverflow

~75s

Adding one to the largest int

What does this Java program print?

public class Main {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE + 1);
    }
}
Show the answer and the worked solution

Correct answer: C.

-2147483648

Worked solution

  1. Integer.MAX_VALUE is 2147483647 and the literal 1 is an int, so the addition is performed in 32-bit int arithmetic.
  2. Java specifies wrap-around on overflow rather than an exception, so the result rolls over to the most negative int.
  3. 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.

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.

Question

What does this Java program print?

public class Main {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE + 1);
    }
}

Options

  1. 2147483647
  2. 2147483648
  3. -2147483648
  4. The program does not compile
Show the answer and the worked solution

Correct answer: C. -2147483648

Worked solution

  1. Integer.MAX_VALUE is 2147483647 and the literal 1 is an int, so the addition is performed in 32-bit int arithmetic.
  2. Java specifies wrap-around on overflow rather than an exception, so the result rolls over to the most negative int.
  3. 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