Originally posted by Bob Vel:
Friends,
Following example's answer is 5 and 6.
public class StaticDemo
{
static int i = 5;
static
{
System.out.println("Static code: i = "+ i++ );
}
public static void main(String arg[])
{
System.out.println("main: i = "+ i++);
}
}
I thought the answer should be 6 and 6.
Please explain.
Thanks in advance.
Hi Bob,
The result shows that the post-increment operator (++ right after x) does it's job. What post-increment operator does is that it evaluates the associate expression with the current value of x first. Save the answer. Increment the variable. Then move the saving answer into the result's position.
In your case, two calls to System.out.println("..." + x++) will then yield 5 and 6 since:
The first call will just save the value of 5. Incerement x to 6. Send the value of 5 for answer.
The 2nd call will save the value of 6. Increment x to 7. Send the value of 6 for final answer.
I hope that helps....
Regards,
Lam