aspose file tools*
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 Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "for loop with preincrement?" Watch "for loop with preincrement?" New topic
Author

for loop with preincrement?

adam faith
Greenhorn

Joined: Aug 24, 2002
Posts: 22
Hi,
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> ) {
<block>;
}
Is analogous to:
<init>;
while(<test>) {
<block>;
<next>;
}
So post or pre increment makes no difference...
Cheers, Neil
[ September 14, 2002: Message edited by: Neil Laurance ]
adam faith
Greenhorn

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

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 frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: for loop with preincrement?
 
Similar Threads
please help
Thread doubt
Doubt on Post Increment operator.
Confused with pre and Post increment please help ..
What is the point of having pre-increment operation in for-loop?