• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

simple doubt - Please help !!

 
Abdul Mohsin
Ranch Hand
Posts: 111
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
let's say

Byte b=20;

if(b==20){
// something
}

/*
in statement b==20, b will be unboxed to byte or 20 will be boxed to Byte
*/

please explain.

Regards,

Abdul Mohsin
[ May 10, 2007: Message edited by: Abdul Mohsin ]
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Byte b=20;

if(b==20){
// something
}

/*
in statement b==20, b will be unboxed to byte or 20 will be boxed to Byte
*/

please explain.


Definitely primitive is not going to be boxed before comparison. b will be unboxed before comparison. It is the only way keep this rule OK. ==
comparison results true if one wrapper and another primitive comprises same value. And this comparison is done after unboxing the wrapper. This will always result true.





Thanks,
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree. Boxing 20 would always return false, as you'd compare two different Byte references.
 
Abdul Mohsin
Ranch Hand
Posts: 111
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chandra and Satou for your help !!!

Abdul Mohsin
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Satou kurinosuke:
I agree. Boxing 20 would always return false, as you'd compare two different Byte references.


Ah, but IF it was boxing a value in the range [-128..127] it would be caching the objects, wouldn't it? So you would get true in this case.

But it doesn't box, it unboxes. The rules are in the Java Language Specification.
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think,
unbox first, otherwise you would be comparing references.

Are there any rules? I couldn't find it in JLS.

Autoboxing:


output is :
Less than Check : true
Greater than Check : true
Equality Check : false
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic