The future belongs to those who believe in the beauty of their dreams.Dream BIG!
who dare win!<br />SCJP5(94%)|SCWCD5(86%)|SCBCD(100%)|SCEA in progress
SCJP 5.0
Originally posted by R van Vliet:
The Race is not yet over; Because i have not yet won!!
Originally posted by Luca Romanello:
Hi all
I respectfully disagree with your example. All boolean tests return true, since assigning String literal to String variables means that the jvm take advantage of its String constant pool - so s1 and s2, though both initialized without referencing each other, point to the same object (String) in the pool.
The example made by Fudong is correct, since both str1 and str2 make an explicit call to String constructor, creating two new (and different) instances.
We can find the same (or - better - very similar) behaviour working with int literals in short range (between -128 and 127; even if assigning them to a wrapper via boxing should mean making a new constructor call![]()
):
will print true, while assigning 128 to s1 and s2 will print false.
Hope this helps.
Regards
LR
[ November 20, 2007: Message edited by: Luca Romanello ]
Originally posted by R van Vliet:
(on a slightly pedantic note, i do believe it should return false, only object variables explicitly set to refer to another object should return true, this happening as the result of a VM constant pool optimization seems questionable, but it's a tradeoff that can be defended).
SCJP 5.0
The future belongs to those who believe in the beauty of their dreams.Dream BIG!
The future belongs to those who believe in the beauty of their dreams.Dream BIG!
Originally posted by nico dotti:
Someone correct me if I'm wrong as I'm by no means an expert (yet!):
Using your example Nabila:
If you did the obj==obj2 test here (before the next line) the result will be false as obj1 and obj2 'refer' to different objects. But when you do this:
ojb1 doesn't refer to the object it used to (obj1...itself), it now refers to obj2! So now the are referring to the same object and the '==' will evaluate to true.
And here's a complete program you can compile as bar.java which should resolve any doubts.
The future belongs to those who believe in the beauty of their dreams.Dream BIG!
The future belongs to those who believe in the beauty of their dreams.Dream BIG!
Originally posted by Nabila Mohammad:
I got the "==" part
How about the equals() part..?
The future belongs to those who believe in the beauty of their dreams.Dream BIG!
Never explain yourself to anybody
String s1 ="abc";
String s2 ="abc";
String s1 =new String("abc");
String s2 =new String("abc");
Don't get me started about those stupid light bulbs. |