Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

println() method in Java for Strings equality ... and how it works exactly? [duplicate]

Tags:

java

string

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
like image 707
aniketk Avatar asked Jun 24 '16 08:06

aniketk


People also ask

Why does == work on strings in Java?

== 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.

How do you equal a string in Java?

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.

How do you check if a string is equal to another string in Java?

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.

What is the proper way to compare string values in Java the == operator the equals () string method the operator the operator?

You should use string equals to compare two strings for equality, not operator == which just compares the references.


1 Answers

This is due to operator precedence: "Hello:" + x == y is equivalent to ("Hello:" + x) == y.

Because + has a higher precedence than ==.

like image 104
assylias Avatar answered Oct 26 '22 22:10

assylias