File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes for loop with preincrement? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "for loop with preincrement?" Watch "for loop with preincrement?" New topic

for loop with preincrement?

adam faith

Joined: Aug 24, 2002
Posts: 22
In the following code
for(int j = 0 ; j < 2; ++j)
System.out.println("j =" +j);
I thought the output would be
j = 1
But the output is
j = 0
j = 1
Am i missing something here, i thought the preincrement was done before the the output statement was executed?
Can sombody help, thanks
Neil Laurance
Ranch Hand

Joined: Jul 18, 2002
Posts: 183
Think of it like this:
for( <init>; <test>; <next> ) {
Is analogous to:
while(<test>) {
So post or pre increment makes no difference...
Cheers, Neil
[ September 14, 2002: Message edited by: Neil Laurance ]
adam faith

Joined: Aug 24, 2002
Posts: 22
Thanks Niel
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
As an aside, I tend to prefer "preincrement" for everything unless the (slightly peculiar) postincrement semantios are a vital part of the solution. I find that it's easier to say ("increment i"), easier to understand (it's exactly the same as "i += 1", and looks more like a method call.
I write all my "for" loops using preincrement, and whenever I have a stand-alone increment in a method, I use preincrement too.
Others have different opinions, but I think everyone should decide for themselves rather than just using "i++" because that's the way Kernighan and Richie did it in the first edition of "The C Programming Language".
Think about it. Were you ever confused by an inadvertent use of "i++" ?

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
I agree. Here's the link:
subject: for loop with preincrement?
It's not a secret anymore!