| Author |
Some Problem with Wrapper
|
Mamta Sharma
Greenhorn
Joined: Jun 03, 2008
Posts: 25
|
|
Question is from:-Valiveru's Mock Exam Select the code segments(assuming is part of valid class) below that compile and run correctly with output: We are Equal A.int i = 10; long l = 10L; if( i == l ) System.out.println("We are Equal"); B.int i = 10; Integer ii = new Integer(10); if( i == ii) System.out.println("We are Equal"); C.int i = 10; char c = 10; if( c == i) System.out.println("We are Equal"); D.Integer ii = new Integer(10); Integer jj = new Integer(10); if(ii == jj) System.out.println("We are Equal"); E.String s1 = "Null"; String s2 = "Null"; if( s1 == s2) System.out.println("We are Equal"); F.String s1 = "Null"; String s2 = new String(s1); if( s1 == s2) System.out.println("We are Equal"); Correct answers are A,C,E I agree with above answers.My confusion is with the option D,what i remember is if two Integer wrapper objects have the same values & between -128 to 127 then == operator returns true because they share the same location in memory.I tried to compile but no output is there. Can anyone make it clear for me. Thanks Mamta
|
 |
Anit Nair
Greenhorn
Joined: May 09, 2008
Posts: 12
|
|
Hi, Thats true only if the two instances are created directly by assigning values directly i.e. However,when you create two instance using the constructor, two different objects are created
|
 |
Raphael Rabadan
Ranch Hand
Joined: Jul 05, 2008
Posts: 141
|
|
Integer in the range of -128 to 127 will be equal if created as literal. When you use new, no matter what object you are instantiating, you will have a new Object. So, try it out:
|
SCJP Java 6 (98%) - Story, SCJA (88%) - Story
|
 |
Mamta Sharma
Greenhorn
Joined: Jun 03, 2008
Posts: 25
|
|
Thanks Anit & Raphael, I got it.
|
 |
Jarek Jankowski
Greenhorn
Joined: Jul 05, 2008
Posts: 13
|
|
|
B is also a correct answer. Integer object is unboxed and comparison is made on two ints.
|
 |
Mamta Sharma
Greenhorn
Joined: Jun 03, 2008
Posts: 25
|
|
|
Yes Jarek, you are right.
|
 |
 |
|
|
subject: Some Problem with Wrapper
|
|
|