Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a += a++ * a++ * a++ in Java. How does it get evaluated?

I came across this problem in this website, and tried it in Eclipse but couldn't understand how exactly they are evaluated.

    int x = 3, y = 7, z = 4;

    x += x++ * x++ * x++;  // gives x = 63
    System.out.println(x);

    y = y * y++;
    System.out.println(y); // gives y = 49

    z = z++ + z;
    System.out.println(z);  // gives z = 9

According to a comment in the website, x += x++ * x++ * x++ resolves to x = x+((x+2)*(x+1)*x) which turns out to be true. I think I am missing something about this operator precedence.

like image 701
Ashok Bijoy Debnath Avatar asked Nov 13 '12 21:11

Ashok Bijoy Debnath


People also ask

How the operators are evaluated in Java?

In Java, the operands of an operator are always evaluated left-to-right. Similarly, argument lists are always evaluated left-to-right.

How do you evaluate an expression in Java?

To evaluate expressions containing variables we need to declare and initialize variables: String expression = "x=2; y=3; 3*x+2*y;"; Double result = (Double) scriptEngine. eval(expression); Assertions. assertEquals(12, result);

Does Java evaluate left to right?

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.


2 Answers

Java evaluates expressions left to right & according to their precedence.

int x = 3, y = 7, z = 4;

x (3) += x++ (3) * x++ (4) * x++ (5);  // gives x = 63
System.out.println(x);

y = y (7) * y++ (7);
System.out.println(y); // gives y = 49

z = z++ (4) + z (5);
System.out.println(z);  // gives z = 9

Postfix increment operator only increments the variable after the variable is used/returned. All seems correct.

This is pseudocode for the postfix increment operator:

int x = 5;
int temp = x;
x += 1;
return temp;

From JLS 15.14.2 (reference):

The value of the postfix increment expression is the value of the variable before the new value is stored.

like image 170
jn1kk Avatar answered Oct 06 '22 00:10

jn1kk


Nothing to do with operator precedence per se, just the order of evaluation. Two things to know here:

  1. x++ is the postfix increment, so the value of x is incremented after it is evaluated
  2. * evaluates the right side then the left side.

Considering point 2, the expression x++ * x++ * x++ can be rewritten more specifically as x++ * (x++ * (x++)).

The whole expression can be written as the procedures:

a = x
x += 1
b = x
x += 1
c = a*b
d = x
x += 1
return c*d
like image 22
Tim Bender Avatar answered Oct 05 '22 23:10

Tim Bender