Weird increments

int n=100;
int num1=++n;
int num2=num1++;
System.out.println(num1+" "+num2);

Gives output as 102 and 101
How?

Num1++ is post increment, so num2 gets 101 and then num1 becomes 102. ++n is pre increment, n increases to 101, and then num1 gets n(101)

4 Likes

Is it executing from bottom?

No, i just said it upside down

The original code is equivalent to the following, “unrolled” version:

int n=100;
// The next two lines are equivalent to the original "int num1=++n".
n++;
int num1=n;
// The next three lines are equivalent to the original "int num2=num1++".
int valueOfNum1BeforeIncrementing = num1;
num1++;
int num2=valueOfNum1BeforeIncrementing;
System.out.println(num1+" "+num2);
3 Likes

Yeah… this gives 102,101?

Yep :slight_smile:

int n=100;
// The next two lines are equivalent to the original "int num1=++n".
n++; // n = 101
int num1=n; // num1 = n = 101
// The next three lines are equivalent to the original "int num2=num1++".
int valueOfNum1BeforeIncrementing = num1; // valueOfNum1BeforeIncrementing = 101
num1++; // num1 = 102
int num2=valueOfNum1BeforeIncrementing; // num2 = valueOfNum1BeforeIncrementing = 101
// num1 = 102, num2 = 101
System.out.println(num1+" "+num2);   
3 Likes

Thank you so much

1 Like

Thank you so much