Veena,
Remember in my original reply I said it was "when" and not what is happening. In
Java and many other languages the increment operator "++" is used in a special way--if it is before the variable it is called a pre-incrment and if it is after the variable it is called a post-increment. The problem you are having is not in understanding the loop construct, but the expression "i=i++". What you think is happening is the same as in "i=i+1", and that is NOT what is happening.
First the assignment operation is done: "i=i" so now we have i set to the value of i, no big deal, but there has not been an increment done at this time, Java has not even considered the increment yet, but the left side has evaluated already to i, that same value as when it started on that expression. Now after the left side has been evaluated the post-increment comes into play to evaluate the right side of the expression and it 1 is added to the value of 0 which is what i is in evaluating the right side of the expression, so the right side has been evaluated to 1. All well and good, but that has been done AFTER the left side has been assigned the initial value of i, which was 0. That is what is called POST-INCREMENT. The incrment happens after the use of the value of the variable.
Not if you put the incrment operator "++" before the variable, that is called PRE-INCREMENT and this happens for "i=++i", i looks to be assigned, Java encounters the pre-increment and says--before the value can be assigned to the left the pre-increment has to be honored, so the evaluation becomes i=1+0 and is assigned the value of 1.
Since in the loop example you gave a post-increment is used, then the value of i is carried forward in the evaluation of the equation "i=i++", hence i is never incremented in the loop, and therefore the loop is infinite--never proceeding past a count of 0, but ever looking to become 5 or more to stop.
consider the following:
The example illustrates post and pre increment operation. If you are going to use pre or post increment, then you need to understand "WHEN" the increment happens, because it can make a huge difference in evaluation.
Les
Veena Pointi wrote:Below is explanation of OCA by Jeanne Boyarsky and Scott Selikoff for sequence of executiong of for statement
1.Initialization statement executes
2.If booleanExpression is true continue,else exit loop
3.Body executes
4.Execute updateStatements
5.Resturn to step 2
So you see i=0 happens only once.As per this explanation both code blocks above should output same thing that is print 1 2 3 4 . Why in case of infinite loop , i is being initialized to 0 everytime and why not in other case?