1

This is not my code and I know this is not the right way to write this. I was asked this in an online test.

public class HelloWorld{

     public static void main(String []args){
        int x = 10;
        x = x++ * ++x;
        System.out.println(x);
     }
}

Ouptut is 120. I don't understand why. Should it not be 132/121 ? Is it JVM dependent?

Ian McGrath
  • 982
  • 2
  • 10
  • 23
  • think ab out the post and pre application of ++ – innoSPG Mar 29 '14 at 00:53
  • 3
    @ᴋᴇʏsᴇʀ he means `132` **or** `121` – Baby Mar 29 '14 at 00:54
  • FYI, Java defines the evaluation order, so that this is not JVM dependent. But don't try this C or C++, where the results could be compiler-dependent. (Not sure about JavaScript, PHP, C#.) – ajb Mar 29 '14 at 00:58

3 Answers3

4

x++ is evaluated first. It's post-increment, so 10 is the value of the expression, then x is incremented to 11.

++x is evaluated next. It's pre-increment, so x is incremented to 12 and 12 is the value of the expression.

The rest is simple multiplication, and 10 * 12 = 120.

This behavior is not dependent on which JVM is used; all JVMs must behave this way, as specified by the Java Language Specification.

The JLS, Section 15.14.2 covers post-increment expressions:

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

The JLS, Section 15.15.1 covers pre-increment expressions:

The value of the prefix increment expression is the value of the variable after the new value is stored.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

This is a common error dealing with the meanings of i++ and ++i.

See What is the difference between ++i and i++?,

Community
  • 1
  • 1
k_g
  • 4,333
  • 2
  • 25
  • 40
0

It is perfect, x++ will make it 10 due to post increment at the time of execution and will become 11 after and ++x will make it 12 at instance due to preincrement. so the output would be 120

Keerthivasan
  • 12,760
  • 2
  • 32
  • 53