Originally posted by Edmund Chiang:
Hi Fellas,
The question goes as such:
What will be the result of compiling and running the following code be?
public class TestClass
{
public static void main(String args[])
{
int k = 1;
int i = ++k + k++ + k;
System.out.println(i+""K);
}
}
The answer: The program compiles and prints 7 and 3
JQ+ comments that we must look at it like ((2)+(2)+(3)) = 7
End value of k is 3
Please help me with this concept!!
Thanks in Advance
Best Regards
Edmund
Hi Edmund,
This has to do with pre-increment vs. post-increment operators. As JQ+ suggested,
you should look at the expression as:
int i = ((++k) + (k++) + k);
++k (pre-increment ++operator) says "increase my value by 1 before using it in the expression." k is therefore will take a new value of 2 and the above expression will look like this:
int i = ((2) + (k++) + k);
k++ (post-increment operator++) says "use my current value before increase its value by 1." So in the above expression, (k++) will still be evaluated with a value of 2... hence the above expression looks like this:
int i = ((2) + (2) + k);
After the post-increment, k = 3 and the above expression finally looks like this:
int i = ((2) + (2) + 3) => i = 7, k = 3;
Hope that helps,
Lam