Can someone please explain why output is false when Line1 is not commented :roll:
What is the type of j after Line 1? is it still Integer or int? If its Integer then I can understand that output will be false. If its int then Output should be true. correct??
Quite a tricky question. I doubt if it would make it on the real SCJP exam. The exam does expect you to know the difference between == and .equals() but it does not attempt to trick you into giving the wrong answer.
Rafael Angarita wrote:Actually, I think that in line Line 1, Autoboxing enters in action and creates a new Integer object. Therefore, i and j refer to different Integer objects.
At line 8 (line 1 in comment), autoboxing actually doesn't create a new Integer object -- it gets the object from the Integer cache. It is the code (at line 6) that creates a new object, instead of getting it from the integer cache. If line 6 also used autoboxing (as below), then it would have compared, as they would have been the same reference from the cache.
When you use == on two objects then it compare the bit pattern stored in the object. That's why when you comment the line, the bit pattern stored in both integer object is same. try equals method which compare two object if they are meaningfully equal. Integer class override the equals method so it would work.
Note to self: don't get into a fist fight with a cactus. Command this tiny ad to do it:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop