File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes for loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "for loop" Watch "for loop" New topic

for loop

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
class method
{public static void main(String a[])
{int num[] ={1,2,3,4};
for (int i = 0;i < num.length;++i)
The o/P;1,2,3,4.
But shouldnt it be 2,3,4.Since for every iteration first i is incremented by 1 and other statements are executed.IF for statement is replaced by
for(int i = 0; i < num.length; i++)
the o/p is same.
Anyone pl. explain me how is the program working?

[This message has been edited by Jim Yingst (edited August 03, 2000).]
[This message has been edited by avn (edited August 03, 2000).]
Ranch Hand

Joined: Jul 19, 2000
Posts: 50
I think the given answer is correct.The iteration part executes after the first execution of the loop.So it starts with i = 0 here.
Hope I made it clear.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
when the program executes the for loop first time it takes initilization value ,executes conditional expression and then if true enters the for loop ,the lost incremental expression ++i (i++) will be executed after every time body of the if loop completes.So i++ or ++i doesnot make difference out here .
now traverse the loop u will get 1,2,3,4
i hope this explanation helps
I agree. Here's the link:
subject: for loop
It's not a secret anymore!