This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes what is the Output? and why? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "what is the Output? and why?" Watch "what is the Output? and why?" New topic
Author

what is the Output? and why?

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
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

Joined: Jul 17, 2001
Posts: 173
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
 
subject: what is the Output? and why?
 
Similar Threads
charAt problem....
Increment Test
deal with loops.....
why??
Question from jqplus