File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Tricky For Loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Tricky For Loop" Watch "Tricky For Loop" New topic
Author

Tricky For Loop

Vinny Chun
Greenhorn

Joined: Dec 06, 2001
Posts: 24
I came across a tricky question in the Net.
class Question
{
public static void main(String[] args)
{
int i, j;
for (i=0, j=0; i+j < 20; ++i, j+=i--)
{
System.out.println("i+j = " + (i+j));
}
}
}
What does this program print out?
a.5
b.8
c.13
d.Compile error
Answer a, b and c are correct.
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
The thing you have to notice here is that i is always 0, and thus the values of j are printed from 0 to 19... That's tricky !
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Vinny
Were you askig a question or just posting interesting code? On the chance that you were asking a question here is a break down of what happens in this loop.
1st iteration:
i=0, j=0
prints: 'i+j = 0'
2nd iteration:
i=0, j=1
prints: 'i+j = 1'
3rd iteration:
i=0, j=2
prints: 'i+j = 2'
4th iteration:
i=0, j=3
prints: 'i+j = 3'
and so on with i staying 0 and j increasing by 1 each time. This is because in the for loop the increment part: '++i, j+=i--' i is both incremented by one then decremented so it never increases. Meanwhile the expresion for j uses the incremented value of i before it is decremented. The incremented value of i is always 1 so j increases by 1 each time.
If you weren't looking for an explaination then please ignore all of this.

What does this program print out?
a.5
b.8
c.13
d.Compile error
Answer a, b and c are correct.[/B]

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform


Dave
Vinny Chun
Greenhorn

Joined: Dec 06, 2001
Posts: 24
Dave and Val, thanks for your explanation. I am more clear with this For Loop now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Tricky For Loop
 
Similar Threads
on switch expression
Flow Control -JQ+
For loop question
confusing for Loop.
a question for "For loop".