1
public class HelloWorld {
    public static void main(String[] args) {
        String s1="yes";
        String s2="yes";

        System.out.println("-------The result is-----"+ s1==s2);
        System.out.println("-------The result is-----"+ (s1==s2));    
    }
}

Why the above code produce the output
"false"
-------The result is-----true

Tanmay Patil
  • 6,882
  • 2
  • 25
  • 45
Rahul Goyal
  • 203
  • 1
  • 8

4 Answers4

5

First of all, you should not be comparing strings with ==, but with equals().

There's also the issue of operator precedence. This:

"-------The result is-----"+ s1==s2

is the same as:

("-------The result is-----"+ s1) == s2

because + has higher precedence than ==.

Jesper
  • 202,709
  • 46
  • 318
  • 350
0

when you are comparing strings you should change up == to be .equals() due to the fact that .equals() compares the contents of the strings to each other or is used to compare objects. == checks for reference equality or is used to compare primitives. I changed your code below:

System.out.println("-------The result is-----"+ (s1.equals(s2)));
mig
  • 142
  • 7
0

You are comparing the references of s1 and s2, and since you defined them separately, they don't have the same references. To compare the strings, please use equals or equalsIgnoreCase

anirudh
  • 4,116
  • 2
  • 20
  • 35
0
'+' > '=='

so

"-------The result is-----"+ s1==s2 becomes

("-------The result is-----"+ s1)==s2 and hence false.

RKC
  • 1,834
  • 13
  • 13