+ 3
String handling(==) in java
Why in the following code output is different as we have used s1 both the time to initialize s2 &s3 https://code.sololearn.com/cJjFWWu25JZl/?ref=app
7 Answers
+ 4
Because when you declare a string with "new" you are creating a new object and you compare not only the value in the string but also the place where string is stored. In this case it's an object. That's why the result is false.
+ 4
I had the same problem long ago so I think I am gonna explain better....
See in java we used == operator to compare the values stored in 2 variables Maybe int type ,double,char,boolean etc but String type is Simply a class so whenever we create a String variable we create an Object (Instance) of the String class
so, when we use == operator with objects it checks whether both the objects are same(have the same memory location in the System) which i think is not possible for two distinct objects they may store the same value but both are unique in their own way
so
The solution:
while comparing Strings you should use one of these:
1)s1.equals(s2);
2)s1.compareTo(s2)
Hope I helped.....
Regards
tell me if it's clear now or I should make it more clear
Thanks.....
+ 4
if you had 2 separate strings both called "earth" and you compared them using == they would be equal as inside the string pool theres only one reference created for that object. If you created a "new" String literal called "earth" and compared it to the previous String "earth" although they both have the same value they would not be equal as the new "earth" String is stored in heap and the other String is stored in the string pool both in diffrent memory locations. rule of thumb always compare String values using x.equals(y); method
+ 2
The operator "==" compares the addresses of the two pointers so doesn't compare the strings. If you want to do it, use String.equals.
+ 2
one thing is that why s1 & s2 are then true?
+ 2
harshit that's because compiler treats s1 as a sequence of characters rather than an instance of String class but s3 is declared as an object of String class so it is treated as an object and memory location is being compared
on the other hand s1 and s2 being declared using the String literal are having their user defined values compared rather than memory address
+ 1
hii