Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

JQ + Ques Id : 1002821815364

sonir shah
Ranch Hand
Posts: 435
What will the following program print?
class Test
{
public static void main(String args[])
{
int i=0, j=0;
X1: for(i = 0; i < 3; i++)<br /> {<br /> X2: for(j = 3; j > 0; j--)
{
if(i < j) continue X1;
else break X2;

}
}
System.out.println(i+" "+j);
}
}
If i<3, then how is it possible for 'i' to get the value 3.
And the same case is with 'j'

ersin eser
Ranch Hand
Posts: 1072
1 st iteration i== 0 j == 3 thus i < j true skip inner i++ @ outer
2nd iteration i== 1 j == 3 thus i < j true skip inner i++ @ outer
3rd iteration i== 2 j == 3 thus i < j true skip inner i++ @ outer
4th iteration i== 3 j == 3 thus i < j false skip(break) inner because of else path . outer ends because 3<3 false then you fall out and print i == 3 and j == 3 ( becuase of inner j=3 ! )
pencil & paper thats what u will be given and use them !

------------------
Have a nice day, Unless you've made other plans.
[This message has been edited by ersin eser (edited December 30, 2001).]

Arsho, Ayan
Ranch Hand
Posts: 60
<code>
My Question is same as Sonir's, how will i iterate upto 3 when the condition is i<3, shouldn't the iteration stop after 2.
Thanks
</code>

Jim Hall
Ranch Hand
Posts: 162
If i never reached 3 or greater, we would be in an infinite loop.

Rick Reumann
Ranch Hand
Posts: 281
Originally posted by ersin eser:
1 st iteration i== 0 j == 3 thus i < j true skip inner i++ @ outer
2nd iteration i== 1 j == 3 thus i < j true skip inner i++ @ outer
3rd iteration i== 2 j == 3 thus i < j true skip inner i++ @ outer
4th iteration i== 3 j == 3 thus i < j false skip(break) inner because of else path . outer ends because 3<3 false then you fall out and print i == 3 and j == 3 ( becuase of inner j=3 ! )
pencil & paper thats what u will be given and use them !

I believe your 4th explanation here is not correct. When i = 3, The X2 block ( i < j section) will not even be evaluated (since i is not less than 3 ). However since the local variable i is set to 3 it will be 3 when it is printed. With j, the variable never gets set to anything less than 3 since i is always evealuating to be less than 3 and thus the continue X1 gets executed. Maybe I'm wrong, but I think that's how it's working.

Ragu Sivaraman
Ranch Hand
Posts: 464
when i becomes 3 the condition fails and the loop breaks ... system.out prints out 3,3
Ragu