Java assignment operator execution

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:

  1. 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”)
  2. figure out the parameters (i.e. evaluate x = y, which will change x to point to the String “goodbye” and also return a reference to that String)
  3. 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)