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

Options
- Compiler error
- Runtime Exception
- True
- False


CORRECT ANSWER : False

Discussion Board
EXPLANATION

because == is used to compare 2 objects that means two objects refers to same memory location or not .

In this case we are using new operator that means both objects have different memory location that's why answer is false.

one more thing : if we remove new
Integer a = Integer(5)
Integer b = Integer(5)

that means both of the objects ( a and b ) refers to same memory location because java uses string pool and assign same memory location then answer will be true in that case.


Jitender Kumar 11-8-2015 06:00 AM

chemistry

pls i need it in my exams

olajitan victor 06-17-2015 10:02 AM

answer to question

I think this is because you compare objects, which have different id. You need to get the value from each of those objects.

i.e.
Integer a = new Integer(5);
Integer b = new Integer(5)

if(a.intValue() == b.intValue() ){


}

Therefore by using intValue() you get back the primitive type to compare and not the object.


Another way is the one below, but i am not sure if it returns primitive type
if(a.compareTo(b) == 0){

}

Tas 12-4-2014 05:36 AM

even though both are intialized with same values,why is it false!

why the answer is false?can any one xpln?


cherry 10-15-2014 09:40 AM

Write your comments


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)


Advertisement