• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Some Problem with Wrapper

 
Mamta Sharma
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Mamta Sharma
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Anit & Raphael,
I got it.
 
Jarek Jankowski
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
B is also a correct answer. Integer object is unboxed and comparison is made on two ints.
 
Mamta Sharma
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Jarek, you are right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic