Multiple choice java

Integer a = new Integer(2); Integer b = new Integer(2); What happens when you do if (a==b)?

  1. Compiler error

  2. Runtime Exception

  3. True

  4. False

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

To solve this question, the user needs to understand the concept of object comparison in Java and how it differs from primitive type comparison.

In Java, objects are compared using the == operator. When comparing two objects using ==, Java checks if the two objects refer to the same memory location. If they do, the == operator returns true; otherwise, it returns false.

Now let's go through each option and explain why it is right or wrong:

A. Compiler error: This option is incorrect. There is no compilation error in the given code. The code will compile successfully.

B. Runtime Exception: This option is incorrect. There is no runtime exception in the given code. The code will run without throwing any exceptions.

C. True: This option is incorrect. Although the values of a and b are both 2, the variables a and b are objects of the Integer class. When comparing objects using ==, Java checks if they refer to the same memory location, not their values. In this case, a and b are different objects, even though their values are the same. Therefore, a == b will return false.

D. False: This option is correct. As explained earlier, a and b are different objects, even though their values are the same. Therefore, a == b will return false.

The answer is: D. False