Hello Ranchers, I am referring K & B book 1)I am really confused with Boxing,== and euals method.In this book it is mentioned that for ==condition Boolean,Byte,Character and Integer object compares their primitive value but nothing is mentioned for Double and Float object. 2)Also for != this condition for all wrapper object what actually compares their identity or their value please enlighten my knowledge on this topic and correct me wherever i am wrong.
The automatic boxing and unboxing for Double and Float work just like for Integer and the other wrapper types. Thus: should print true.
I don't have a copy of K&B handy right now. But if it indeed doesn't mention performing == comparisons with Double and Float, that's probably because it's usually a bad idea in the first place to directly compare double and float values (even with primitives) due to loss of precision. For example: prints false on my machine, even though mathematically d1 and d2 ought to be equal.
As for your question about how auto-boxing works with the != operator, if you're comparing a wrapper object to a primitive, then the comparison will be based on their values. But if you're just comparing two wrapper objects, no auto-boxing/unboxing occurs, so you're just comparing their references. Example: will print "false true". [ November 02, 2007: Message edited by: Kelvin Lim ]
Correct me if I am wrong here....but I thought the reason that you can't box long, double, and float is that they can't be safely converted to the appropriate range.....Per the K&B book it states ( on page 236)
Autoboxing can only be used for the following primative/Object types.....
Boolean Byte Character from \u0000 to \u007f (7f is 127 in decimal) Short and Integer from -128 to 127
I am assuming it has to do with the available bits that it sets aside to keep up performance speeds....(-128 to 127 is 7 bits). If you had a double/float that was 126.99999 it would take up more than the 7 bits allowed so you would lose precision.
That is my take on things, correct me if I am wrong though...
Autoboxing can only be used for the following primative/Object types.....
Boolean Byte Character from \u0000 to \u007f (7f is 127 in decimal) Short and Integer from -128 to 127
I'm afraid that this is *not* true. I believe autoboxing should work for all the primitve types -- and for the full range of the types.
The list that you are quoting is for the cache. Basically, when you box an integer within the -128 to 127 range, it will use an already instantiated object from the integer cache. For outside the range, it is not required to use the cache -- so the current implementation of the Sun JVM will instantiate a new Integer object.