Java strings: program output not as expected
String s="abc";
String s1=s;
s=s+"d";
System.out.println(s==s1 +" "+ s.equals(s1));
System.out.println(s.equals(s1));
The above code is written in java. I thought the output of the above program might be
false false
false
but the actual conclusion
false
false
Can someone explain why this is the result and why not like the previous one.
Thanks in advance.
source to share
Let's analyze what's going on here:
System.out.println(s==s1 +" "+ s.equals(s1));
You have boolean + string + boolean. But keep in mind that operators ==
and +
got different priorities (see. Http://bmanolov.free.fr/javaoperators.php ).
As you can see, the + operator has higher precedence and is therefore executed first. This brings up the following:
System.out.println(s == (s1 +" "+ s.equals(s1)) );
As you can see, the line s1
will be appended to " "
, and the rest is false
boolean.
So you have
System.out.println(s == "someString");
which is false and that's why you get "false"
as output.
source to share