• Post Reply Bookmark Topic Watch Topic
  • New Topic

Integer Comparison  RSS feed

 
Daniel Wendhausen
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

One doubt in my mind.. hope someone can help me
Why the first statement prints true, and the second false?
 
Praveen Kumar M K
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Topic for you to study today - Integer pooling.

And welcome to Javaranch!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, note that when applied to objects (like Integer), the == operator compares references.

Next, note that these assignments imply boxing conversions (also called "autoboxing") from type int (primitive) to Integer (object).

And according to JLS - 5.1.7 Boxing Conversion...

If the value p being boxed is ... an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

It says somewhere, but I can’t seem to find it at present, that Integer values between -128 and +127 inclusive are cached, rather like handling of String literals. So two references to Integer i = 123; will produce the same object, but two references to Integer ii = 999; probably won’t.

I have found where it mentions caching: here and here.
 
Daniel Wendhausen
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Little late thanks, but thanks for clarifying this to me guys
 
Manoj Kumar Jain
Ranch Hand
Posts: 198
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this might help you.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You’re welcome (and that other link Manoj Kumar Jain quoted might be useful).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!