2

What i have,

suppose I am creating two object like below,

String s1 = "abc";
String s2 = s1;

System.out.println("== comparison "+ s1==s2);

i am expecting the output is

== comparison true

but i get

false

What is the problem?

I am not getting output as my expectation.

Question why it is not matching the expected output.

please reply and explain why it is coming like this.

Thanks in advance tofek khan

venergiac
  • 7,469
  • 2
  • 48
  • 70

4 Answers4

10

It is because of operator precedence.

The + operator has a higher precedence than ==.

Thus you compare the concatenation of "== comparison " + s1 with s2. Since strings are immutable a new string instance is created that contains "== comparison abc" and this instance can never be the same as s2, because s2 still references "abc".

Use this instead

"== comparison " + (s1 == s2)
René Link
  • 48,224
  • 13
  • 108
  • 140
0

Your code

System.out.println("== comparison "+ s1==s2);

is actually doing

System.out.println(("== comparison "+ s1)==s2);

try

System.out.println("== comparison "+ (s1==s2));
piet.t
  • 11,718
  • 21
  • 43
  • 52
0

Because it prints ("== comparison " + s1) == s2, which is obviously false

This is what you actually need

System.out.println("== comparison " + (s1 == s2));
Erik Ghonyan
  • 427
  • 4
  • 12
0
System.out.println("== comparison "+ s1==s2);

This should be changed to

System.out.println("== comparison "+ (s1==s2));

in order to prepare the comparison result in advance of text output. Also get used to comparing Strings with .equals() method, because you probably want to compare the values, not check for reference equality. See How do I compare strings in Java?

Community
  • 1
  • 1
Dropout
  • 13,653
  • 10
  • 56
  • 109