• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

what is the Output? and why?

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class TestClass
{
public static void main(String args[])
{
int k = 0;
int m = 0;
for ( int i = 0; i <= 3; i++)
{
k++;
if ( i == 2)
{
// line 1
}
m++;
}
System.out.println( k + ", " + m );
}
}
 
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi sonir,
The answer is going to be 4, 4. The reason for this is that the for loop executes 4 times. The counter (i) is set to 0. The loop executes while i <=3 (less than or equal). So this is how the counter gets incremented:
loop 1: 0<=3 k =1, m=1
loop 2: 1<=3 k =2, m=2
loop 3: 2<=3 k =3, m=3
loop 4: 3<=3 k =4, m=4
The if statement does nothing in this class. It's just there to try and throw you off.
Hope that helps,
/rick
 
reply
    Bookmark Topic Watch Topic
  • New Topic