• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper Class

 
Geetha Arthanari
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please explain this output:

public class Example
{
public static void main(String[] args)
{
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 127;
Integer i4 = 127;
Integer i5 = 128;
Integer i6 = 128;
System.out.println(i1==i2);
System.out.println(i3==i4);
System.out.println(i5==i6);

}
}

Output is:
true
true
false
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15354
39
Android IntelliJ IDE Java Scala Spring
 
Saurabh Verma
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,Geetha

I modified your code.



And the output is


This is because == compares reference, not values. This operator compares two values to see if they refer to the same object.
 
Geetha Arthanari
Greenhorn
Posts: 25
 
Geetha Arthanari
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Saurabh,
I'm asking why i1 and i2 are equal. i3 and i4 are equal but i5 and i6 are not equal.
 
dipayan chatterjee
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hii geeteha i1 ,12 ,i3,i4,i5,i6 are all different instances of the Integer wrapper class and saurabh has mentioned the == ooperator returns true only when both the objects are indeed one ,which in our case is not true hence the output will be

false
false
false
 
Henry Wong
author
Marshal
Pie
Posts: 21185
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Geetha Arthanari:
Hi Saurabh,
I'm asking why i1 and i2 are equal. i3 and i4 are equal but i5 and i6 are not equal.


The boxing of integers uses an integer cache. Basically, -128 to 127 are cached when they are boxed, hence, you always get the same one during boxing of numbers in this range.

Interestingly, the specification states that this range must be cache, but it makes no mention of what happens outside this range. This means that in the future, with a new JVM, i5 and i6 may be equal.

Henry
 
Geetha Arthanari
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all of you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic