Machine-translated by Google. Questions are authored in English.
Top

Discussion

The program is run with java -ea Item60 - what will be the output?

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

  • A.The program prints -2147483648
  • B.Compilation fails.
  • C.The program prints 2147483648
  • D.An AssertionError is thrown.

Answer: D

Adding one to Integer.MAX_VALUE overflows silently and wraps to Integer.MIN_VALUE, which is negative. The assertion that the result is positive is therefore false and throws. Java does not raise an error on integer overflow, which is why an assertion is one of the few ways to notice it.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.