File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the Output? and why?

 
sonir shah
Ranch Hand
Posts: 435
  • 0
  • Mark post as helpful
  • send pies
  • 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 );
}
}
 
Rick Salsa
Ranch Hand
Posts: 173
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic