I am trying to understand the working of System.out.println() in Java... in following 2 code snippet , why the answer is different and why it do not print "Hello: " string inside println() method ?
public static void main(String[] args) {
String x = "abc";
String y = "abc";
System.out.println("Hello:" + x == y);
System.out.println("x.equals(y): " + x.equals(y));
if(x == y){
System.out.println("Hello:" + x==y);
}
}
Answer is :
false
x.equals(y): true
false
And for second code snippet :
public static void main(String[] args) {
String x = "abc";
String y = "abc";
System.out.println( x == y);
System.out.println("x.equals(y): " + x.equals(y));
if(x == y){
System.out.println(x==y);
}
}
The answer is:
true
x.equals(y): true
true
== is an operator that returns true if the contents being compared refer to the same memory or false if they don't. If two strings compared with == refer to the same string memory, the return value is true; if not, it is false. The return value of == above is false, as "MYTEXT" and "YOURTEXT" refer to different memory.
Java String equals() MethodThe equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.
You should use string equals to compare two strings for equality, not operator == which just compares the references.
This is due to operator precedence: "Hello:" + x == y
is equivalent to ("Hello:" + x) == y
.
Because +
has a higher precedence than ==
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With