In Java, I understand that assignment evaluates to the value of the right operand, so statements like x == (y = x)
evaluate to true
.
This code, however, outputs false
.
public static void main(String[]args){
String x = "hello";
String y = "goodbye";
System.out.println(x.equals(x = y));
}
Why is this? In my understanding, it first evaluates (x = y)
, which assigns x
the value of y
, and then returns the value of y
. Then x.equals(y)
is evaluated, which should be true
since x
and y
should share the same references now, but instead, I get false
.
What is happening here?
First of all: that's an interesting question, but should never come up in "real code", as assigning to the variable you call in the very same line is confusing even if you know how it works.
What happens here is these 3 steps:
- figure out which object to call the method on (i.e. evaluate the first
x
, this will result in a reference to the String "hello") - figure out the parameters (i.e. evaluate
x = y
, which will changex
to point to the String "goodbye" and also return a reference to that String) - call the method
equals
on the result of #1 using the result of #2 as the parameter (which will be references to the Strings "hello" and "goodbye" respectively).
Looking at the byte code produced for that method makes it clear (assuming you're fluent in Java bytecode):
0: ldc #2 // String hello
2: astore_1
3: ldc #3 // String goodbye
5: astore_2
6: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream;
9: aload_1
10: aload_2
11: dup
12: astore_1
13: invokevirtual #5 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
16: invokevirtual #6 // Method java/io/PrintStream.println:(Z)V
19: return
Line #9 is step 1 above (i.e. evaluates x
and remembers the value).
Line #10-12 is step 2. It loads y
, duplicates it (once for assigning, once for the return value of the assignment expression) and assigns it to x
.
Line #13 invokes equals
on the result computed in Line #9 and the result of Lines #10-12.