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

Discussion

What will be the output of the program?

public class Fragment18
{
    static void show()
    {
        int smallest = Integer.MIN_VALUE;
        int magnitude = Math.abs(smallest);
        System.out.println(magnitude);
    }

    public static void main(String[] args)
    {
        show();
    }
}

  • A.The program prints 2147483648
  • B.The program prints -2147483648
  • C.The program prints 2147483647
  • D.Compilation fails.

Answer: B

Integer.MIN_VALUE has no positive counterpart in the int range, so Math.abs cannot represent the answer and returns the argument unchanged, still negative. This is documented behaviour rather than a defect. Math.abs on a long would be needed to get the positive value.

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

Post your comment

Please log in or register to post a comment.