-1

Can someone please explain to me why this code print only false (Not Both are equal: false)

String one = "length: 10";
String two = "length: " + one.length();
System.out.println("Both are equal:" + one == two);
Piaget Hadzizi
  • 702
  • 8
  • 15
Saurav
  • 55
  • 4
  • 2
    @Hülya The OP's question is about why the output is `false` and not `Both are equal: false`. Although comparing strings with `==` is typically wrong, this question is more about how string concatenation works. – Slaw Dec 30 '20 at 09:34
  • @Slaw you're right, I'm removing the comment... – Hülya Dec 30 '20 at 10:18
  • But still duplicate :) : https://stackoverflow.com/q/18238056/10367471 – Hülya Dec 30 '20 at 10:28
  • @Hülya Good find. Marked as duplicate. – Slaw Dec 31 '20 at 04:25

2 Answers2

4
System.out.println("Both are equal:" + one == two);

is evaluated as

System.out.println(("Both are equal:" + one) == two);

i.e. first one is appended to "Both are equal:" , which results in the String "Both are equal:length: 10", and then that String is compared to two, which results in false, so only false is printed.

What you want is

System.out.println("Both are equal:" + (one == two));
Eran
  • 387,369
  • 54
  • 702
  • 768
1

Just put the brackets here:

System.out.println("Both are equal:" + (one == two));
Piaget Hadzizi
  • 702
  • 8
  • 15