1
String r1 = "hello";
String r2 = "hello";
System.out.println("Result: " + r1 == r2);

I tried running this code and i am not getting the String output in the console. The only value getting printed is the r1==r2 result i.e false.

The question here is I am expecting the output to be "Result: false" and why is false just getting printed.

Also i understand that .equals should be used, I just wanted to know why the result is such in the given scenario.

It would be great if some one can point to relevant documentation and help why this is the behaviour.

  • 2
    Strings are compared with .equals() in Java https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – tgallei Sep 07 '20 at 11:20
  • @kembytes but two string instantiated like this are pointing to the same place in string pool in JVM therefore it "should" return 'true' - the full explanation is already posted as an answer – m.antkowicz Sep 07 '20 at 11:22
  • 3
    This is **not** a problem with `==` instead of `equals`. In fact `r1==r2` would be true. This is a problem with operator order of `+` and `==`. The string `"Result: " + r1` is not equal to `r2`. – khelwood Sep 07 '20 at 11:23

3 Answers3

8

Indeed the output is "false" because first the concatenation is done so it is "Result: hello" and then it is compared to r2 ("hello") which returns false. That's why you see "false" in console.

If you want to see "Result: true" you need to use equals instead of == because that's how we compare Strings in java. See below post to understand differences: How do I compare strings in Java?

If you really want to compare them using "==" you need to add brackets so the comparison will be first before concatenation.

    String r1 = "hello";
    String r2 = "hello";
    System.out.println("Result: " + r1 == r2); // output: "false"
    System.out.println("Result: " + r1.equals(r2)); // output: "Result: true"
    System.out.println("Result: " + (r1 == r2)); // output: "Result: true"
Rafał Sokalski
  • 1,817
  • 2
  • 17
  • 29
1

Because it was processed as

("Result: " + r1 ) == r2

which is false. It was processed in this way because + has a higher priority than ==.

What you need to do to get the string as well is

System.out.println("Result: " + (r1 == r2));

which will give you Result: true

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

To compare strings and print the way you want you should use method equals(). Like this:

String r1 = "hello";
String r2 = "hello";
System.out.println("Result: " + r1.equals(r2));
Grinnex.
  • 869
  • 2
  • 12
  • 23