+ 22
Strange behaviour in String equality comparison.
Assume these variables: String a = "hi"; String b = "hi"; String g = a + b; String f = "hi" + "hi" String h = "hihi"; these are the comparison results: (a == b) : true (g == h) : false (f == h) : true what is happening here? are string imediates different from string variables in comparison? you can see the results here: https://code.sololearn.com/c8crILfg4FTb/?ref=app
7 ответов
+ 7
if you used
"=="
it compair the reference id of object in pool area
and pool area have some characteristics
1.->in pool area GC does not work.
2.duplicate object not allowed.
now see you problem
a="hi";
b="hi"
c=a+b
f="hi"+"hi"
h="hihi";
so
for frist command execution that happen.
1000-->address of memory
[hi]-->name of memory is a
1000
[hi]-->name of memory is a and b
note here new object is not created.
2000-->address of memory g
[a+b]-->name of memory is g
3000 -->address of memory f
[hihi]-->name of memory f
and variable h point the same location same as f
it mean that
f==h--> give you output true because they point same address like 3000.
a==b-->give the output true
because they point the same address like 1000
now
when you do this
String a=new String("hi");
how many object is created by this code
that ans is two
one in heap
2000
[1000]
heap object store the reference id of pool object
and second one in pool
1000
[hi]
+ 18
Mayank Rampuriya you're welcome ✋😊
+ 17
Arun Tomar thanks for your complete explanation. now I get it 👍
+ 7
use . equals() not ==
+ 3
this is because '==' checks if the reference to an object is the same.
a and b are pointing to the same place in memory.
g is a reference to a new place, created especially to store the result of a+b
f and h are equals due to optimisation by the compiler (possible because they are initialized with hard coded strings)
The method equals() can be used to compares the content.
+ 3
This thread cleared my doubt too!
Thanks Amir
+ 1
Are you using .equals instead of ==?