Stephan van Hulst wrote:Byte, Short, Character and Integer put their instances in their own respective pools, in the same way String does; with the exception that String does it with every literal, while the former classes only do so for byte-sized values.
So if you assign the same byte-sized literal to two different wrapper variables, they will point to the same object. I don't think Java does any of this for the decimal classes (Float and Double).
So yes, you can use == to compare wrapper instances that were created this way. You can also use == to compare Strings formed from literals. Personally, I still consider it bad practice. Always use equals() instead.
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Stephan van Hulst wrote :
So yes, you can use == to compare wrapper instances that were created this way. You can also use == to compare Strings formed from literals. Personally, I still consider it bad practice. Always use equals() instead.
== returns false for those Strings, because the references point to two different objects, even though their values are the same
hashcode() returns the same value for the two different Strings, because they have the same value. You will find that equals() returns true.
don't use new String() to create Strings.
adithya narayan wrote:Do you mean the following will always be false ?
If it will always be false then can you please give clarification for the following:
1)When string1 was created with the literal 'abc' , the value went into the string pool (assuming previously the pool is empty).
2)When string2 was created with the same literal 'abc' , the value was found in the pool and assigned the reference to the same object.
Hence, i was thinking that the '==' operator should have worked in the above case.Please correct my understanding if i am wrong.
3)What should be the behavior for the following and why:
hashcode() returns the same value for the two different Strings, because they have the same value. You will find that equals() returns true.
1)Can you please tell the difference between hashcode() and eqauls() method ?
don't use new String() to create Strings.
1)Why shouldn't the new String() be used ?
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Does the API documentation for Object help? That should be the first place you look.adithya narayan wrote: . . . 1)Can you please tell the difference between hashcode() and eqauls() method ?
See whether this recent thread helps. Mike Simmons points out there is very rarely a real use for new String("abc"). . . Why shouldn't the new String() be used ? . . .
Campbell Ritchie wrote:See whether this recent thread helps. Mike Simmons points out there is very rarely a real use for new String("abc")
He was giving me directions and I was powerless to resist. I cannot resist this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|