What will be the result of attempt to compile and the run the following code 1. public class ADirtyOne { 2. public static void main(String args[]) { 3. System.out.println(Math.abs(Integer.MIN_VALUE)); 4. } 5. } Select one correct answer a) causes compilation error b) causes no error and value printed on the screen is less than zero c) causes no error and value printed on the screen is one more than Integer.MAX_VALUE d) will throw runtimeexception answer given is --->b i think option c is also right as (Integer.MAX_VALUE+1) will produce -2147483648 which is less than zero pl.confirm me the right answer and correct me if wrong thanks in adv. sunil
Sunil, I believe you should try to execute these lines of code. I received the following results. TEST 1. System.out.println(Math.abs(Integer.MIN_VALUE)); //-2147483648 TEST 2. System.out.println(Math.abs(Integer.MIN_VALUE+1)); //2147483648 Hope this helps!
hi Cameron... it's probably because the number of negative values an int can hold is NOT equal to the number of the positive values it can contain. in this case it's one more than the number of positive values.
From Java API Documentation abs(int i) method in math class - Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned. Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
pl. read the option 3 again it says that --> causes no error and value printed on the screen is one more than Integer.MAX_VALUE that means if we add 1 to Integer.MAX_VALUE or System.out.println((Math.abs(Integer.MAX_VALUE+1)); which gives -2147483648 which is less than zero so pl. confirm me the right answer
Sunil, "value printed on the screen is one more than Integer.MAX_VALUE" ...try interpretting the phrase as System.out.println((Math.abs(Integer.MAX_VALUE)); + 1 The range of int is -2147483648 to 2147483647. Notice that the absolute value of Integer.MIN_VALUE is one greater then the absolute value of Integer.MAX_VALUE. Chuck