+ 5
Could anyone explain me why the result of this question is b? Aren't a and b identical (same type and same value)?
var a = new String ("Hello"); var b = new String ("Hello"); if (a === b) { alert ("a"); } else { alert ("b"); }
11 Antworten
+ 9
HonFu exactly!
a= "hello"
b= "hello"
Here there's just one "hello" in the string pool and both a and b are referencing to that one instead of having two distinct "hello" for a and b which is the case when you create string using string constructor.
+ 7
You're creating two distinct instances of String class. Although both contains same value but still the two are different instances and hence a==b is false.
+ 4
HonFu lol yeah and that's why it's the easiest language.. No such confusion 😅
+ 2
At least as long as you stick to the builtins with their clear immutable-mutable behavior.
write a class Str that holds a str for you and things may go differently. ;)
+ 2
Thanks to all!! I'm a newbie in programming but now it's clear!!
+ 1
Hm, funny, Python pools them even if you instantiate.
Good to know, thanks!
+ 1
Does Java have a special "===" meaning? I'm not familiar with Java enough to decide if that might be the bug or if it is a legit thing.
+ 1
If we tweak the code a little -
var a = new String ("Hello");
var b = a;
if (a === b) {
alert("a");
}
else {
alert("b");
}
//Now the answer will be - a
//This is because now both the variables
//are referencing the same object unlike
//the original code