Strange behaviour in String equality comparison. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

19th May 2018, 4:44 AM
Amir
Amir - avatar
7 Answers
+ 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]
19th May 2018, 7:52 AM
Arun Tomar
Arun Tomar - avatar
+ 18
Mayank Rampuriya you're welcome ✋😊
20th May 2018, 1:56 AM
Amir
Amir - avatar
+ 17
Arun Tomar thanks for your complete explanation. now I get it 👍
19th May 2018, 6:08 PM
Amir
Amir - avatar
+ 7
use . equals() not ==
19th May 2018, 4:58 AM
᠌᠌Brains[Abidemi]
᠌᠌Brains[Abidemi] - avatar
+ 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.
19th May 2018, 7:31 AM
ifl
ifl - avatar
+ 3
This thread cleared my doubt too! Thanks Amir
20th May 2018, 1:41 AM
Mayank Rampuriya
Mayank Rampuriya - avatar
+ 1
Are you using .equals instead of ==?
25th May 2018, 10:14 AM
Apple Blossom
Apple Blossom - avatar