+ 1

What's the difference between both of them..one is giving true and other false...

https://code.sololearn.com/c39JMSxKHBG7/?ref=app

8th Aug 2019, 4:26 AM
sahana shanbhag
sahana shanbhag - avatar
6 Antworten
+ 4
the thing is that the first two are string literals. that means that they may point to the same object from the memory (heap memory). s3 and s4 are created as new string objects, they are created on the heap, they have the same value but are two different objects. as zemiak pointed out .equals() will help you to compare values, while == operator will check for objects, if it won't be the same object with the same value on the memory then it will return false
8th Aug 2019, 5:27 AM
notqueued
notqueued - avatar
+ 4
nope, it doesn't work like that. "abc" was created on heap for s1. s2 = s1 => s2 pointed to the same object on heap. if you change the value of s1 afterwards, s2 will still point towards the same object from heap, which is "abc". i modified your code to demonstrate that. this is the link: https://code.sololearn.com/cdu9EyCYn8h0/?ref=app
8th Aug 2019, 11:08 AM
notqueued
notqueued - avatar
+ 2
if are storing two same strings as literal, they are optimized as one object, but if they are changed, there are created new individual objects String s1="abc"; String s2="abc"; // true s1=s1+"d"; s2=s2+"d" // false
8th Aug 2019, 12:52 PM
zemiak
+ 1
s1,s2 are same object s3,s4 are not same object use s3.equals(s4)
8th Aug 2019, 5:21 AM
zemiak
+ 1
If both s1 and s2 are same objects then shouldn't both change if I change value of one...?!!
8th Aug 2019, 10:44 AM
sahana shanbhag
sahana shanbhag - avatar
+ 1
Now I understood...thanks alot notqueued
8th Aug 2019, 12:22 PM
sahana shanbhag
sahana shanbhag - avatar