Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a = (a++) * (a++) gives strange results in Java [closed]

I'm studying for the OCPJP exam, and so I have to understand every little strange detail of Java. This includes the order in which the pre- and post-increment operators apply to variables. The following code is giving me strange results:

int a = 3;  a = (a++) * (a++);  System.out.println(a); // 12 

Shouldn't the answer be 11? Or maybe 13? But not 12!

FOLLOW UP:

What is the result of the following code?

int a = 3;  a += (a++) * (a++);  System.out.println(a); 
like image 405
Marius Avatar asked Nov 07 '11 16:11

Marius


2 Answers

After the first a++ a becomes 4. So you have 3 * 4 = 12.

(a becomes 5 after the 2nd a++, but that is discarded, because the assignment a = overrides it)

like image 179
Bozho Avatar answered Sep 28 '22 16:09

Bozho


Your statement:

a += (a++) * (a++); 

is equivalent to any of those:

a = a*a + 2*a a = a*(a+2) a += a*(a+1) 

Use any of those instead.

like image 44
Rok Kralj Avatar answered Sep 28 '22 17:09

Rok Kralj