This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Question from jqplus

K2Joshi
Greenhorn
Posts: 17
Hi All,
I have the following code , i have no clue why i am getting the out put as 3,3. Please help me.
public class Operator
{
public static void main(String args[ ] )
{
int k = 0;
int m = 0;
for ( int i = 0; i <= 3; i++)
{
k++;
if ( i == 2)
{
i=10; // line 1
}
m++;
}
System.out.println( k + " , " + m );
}
}

Ketu

srikrish
Ranch Hand
Posts: 63
k2,
During the loop, when i becomes 2, k gets incremented from 2 to 3. Then i gets set to 10 (by line 1). But the for loop is still on and it does not check for the value of i until the current iteration is completed. And the iteration for i's value of 2 is not completed until m is incremented to 3. After this, i is incremented to 11 (by the for loop) and then its value is checked. Since this is greater than 3, the control goes gets out of the for loop and goes to the println statement. Since the current values of k and m are 3, you get 3,3 as the o/p.
Hope this helps.
[This message has been edited by srikrish (edited September 13, 2000).]

K2Joshi
Greenhorn
Posts: 17
Thanks a lot srikrish,
Ketu

weisheZhao
Greenhorn
Posts: 18
if u try to compile and run this code, u will see the clue of the running.
public class Operator
{
public static void main(String args[ ] ) {
int k = 0;
int m = 0;
for ( int i = 0; i <= 3; i++) {
k++;
if ( i == 2) {
i=10; // line 1
}
m++;
System.out.println("k=" +k + " , " +" m=" +m +", i=" +i);
}
System.out.println( k + " , " + m );
}
}
output:
k=1 , m=1, i=0
k=2 , m=2, i=1
k=3 , m=3, i=10
3 , 3