Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
x++;
System.out.println(x);
}
}-2147483648
- Expecting
2147483648:xis anintwhose maximum is 2147483647, andx++keeps the type, so the value wraps to -2147483648. - Expecting an error or an exception: Java does not check
intarithmetic for overflow; only methods such asMath.addExactthrow.
- How would you add one to
Integer.MAX_VALUEand get 2147483648? - What does
Math.addExact(Integer.MAX_VALUE, 1)do?