int n=100;
int num1=++n;
int num2=num1++;
System.out.println(num1+" "+num2);
Gives output as 102 and 101
How?
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)
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);
Yeah… this gives 102,101?
Yep
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);
Thank you so much
Thank you so much