+ 4
Why does this code outputs false?
public class Program { public static void main(String[] args) { String hi = "leftrightdownup"; String he = "leftrightdownup"; String ney = ""; System.out.println(he == hi); int count = 1; while(count>0){ ney += he; count--; } System.out.println(ney==he); } }
10 Réponses
+ 5
Tedd Bug🐝
In java, the equals() method is defined in the Object class and the String class is overriding the equals() method. In String class equals() method is used for String comparison in Java. We can compare two string by use of equals() method. It compares the values of string for equality. This method compares the original content of the string and returns the value of boolean. If any character is not matched, it returns false. If all characters are matched, it returns true.
firstString.equals(secondString)
If the both strings are equals it will return true otherwise false. It will compare the original content of both strings.
This operator is also used to compare the strings. It doesn’t compare the actual value of the string. It compares the reference of string. The main difference of equals() and == operator is, The equals always compare the value of string but the == operator compares the references of strings.
https://javagoal.com/string-comparison-in-java/
+ 3
MitchHuber thanks!
+ 2
Jayakrishna🇮🇳 thanks, I've just started java after spending sometime with python, thinking they are same.
+ 2
MitchHuber but why is it that the first comparison I made outputs true?
What's the difference between the first and the second comparison?
+ 2
Jayakrishna🇮🇳 thank you so much
+ 2
if you want to check comparison of string you use equals method without using == this sign.
String s = “asd”;
String s1 = “asd”;
s.equals(s1);//this is correct way to compare string variables
+ 1
== compares Refference comparison..
Use equal method, it compares content.
he.equals(hi)
+ 1
When comparing strings in java you should use the .equals method. (EX. ney.equals(he)) For more on this, you can visit https://www.geeksforgeeks.org/difference-equals-method-java/
+ 1
Java uses separate string pool for its immutable strings.. I think, May be that's the difference..
You're welcome.. Tedd Bug🐝
+ 1
In java, when you define a string value, if value already in the string pool then it just same Refference is assigned to new string object. If there is no "string value exits then it create a new one..
So in first both strings points same location.. and == is Refference identity..
In 2nd case, the string ney is formed from 2 different references, result is forms a new Refference, it don't directly point to a new value, instead it points the addition of those 2 references value. hence it returns false on Refference comparison....