Saturday 4 April 2020

Why does (a == (a = b)) not same as (a = b) == a?

The result of ‘(a == (a = b))’ is not same as ‘(a = b) == a’. It is because, as per Java specification, left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

Let’s see an example.

For int i = 2; int j = i * (i = 3);
Above snippet is evaluated like below.
int j = i * (i = 3)
       = 2 * (i = 3)
       = 2 * 3
       = 6

For int i = 2; int k = (i = 3) * i;
Above snippet evaluated like below.
int k = (i = 3) * i
        = 3 * i
        = 3 * 3
        = 9

Find the below working application.

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  int i = 2;
  int j = i * (i = 3);
  int k = (i = 3) * i;

  System.out.println("j : " + j);
  System.out.println("k : " + k);
 }

}

Output
j : 6
k : 9

Similarly let’s evaluate the expression 'a == (a = b)' for a = 1 and b = 3.

expression = a == (a = b)
           = 1 == (a = b)
           = 1 == (a = 3)
           = 1 == 3
           = false
          
Let's evaluate the expression '(a = b) == a' for a = 1 and b = 3.
expression = (a = b) == a
           = (a = 3) == a
           = 3 == a
           = 3 == 3
           = true

Find the below working application.

App.java
package com.sample.app;

public class App {

    public static void main(String args[]) {
        int a = 1;
        int b = 3;

        System.out.println("a == (a = b) : " + (a == (a = b)));
        a = 123;
        System.out.println("(a = b) == a : " + ((a = b) == a));
    }

}

Output
a == (a = b) : false
(a = b) == a : true

Reference

You may like

No comments:

Post a Comment