aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes simple doubt - Please help !! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "simple doubt - Please help !!" Watch "simple doubt - Please help !!" New topic
Author

simple doubt - Please help !!

Abdul Mohsin
Ranch Hand

Joined: Apr 26, 2007
Posts: 111

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 ]

Regards, Abdul Mohsin
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707

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,


cmbhatt
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

I agree. Boxing 20 would always return false, as you'd compare two different Byte references.


[My Blog]
All roads lead to JavaRanch
Abdul Mohsin
Ranch Hand

Joined: Apr 26, 2007
Posts: 111

Thanks Chandra and Satou for your help !!!

Abdul Mohsin
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
John Stone
Ranch Hand

Joined: May 04, 2007
Posts: 332
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: simple doubt - Please help !!
 
Similar Threads
Question regex
What's the reason ?
Cleared SCJP 1.5 with 94% :)
Any Solution of Deadlock?
HashMap StackOverflowError problem - please explain me