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 i++ and - -i 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 "i++ and - -i" Watch "i++ and - -i" New topic

i++ and - -i

bobby chaurasia
Ranch Hand

Joined: Mar 30, 2002
Posts: 84
This is with regard to using ++ & -- with loops
1) with for( int i = 0; i < 10; i++ )
i++ and --i does not make any difference.
2) However with "while" and "do" operators it does make a difference.
Is there any thumb rule or clever improvisation that helps in speeding things. I tend to take a lot of time on these...
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
If you put the ++, -- operators in the second expressions of the for clause; there, the result also would be affected whether they are post or pre operators.

SCJP2. Please Indent your code using UBB Code
shweta mathur
Ranch Hand

Joined: Sep 23, 2002
Posts: 109
Bobby, you need to be very clear how for loop works.
As Bose said if you are placing i++ in loop condition & not the increment expression, then it is same like while-do loop.
Note the following-
1) Syntax of while statement
while(<loop condition>
<loop body>
2) Syntax of do-while statement
<loop body>
while(<loop condition> ;
3)Syntax of for statement
for(<initialization>;<loop condition>;<increment expression>
<loop body>
which is equivalent to
while (<loop condition> {
<loop body>
<increment expression>
Therefore if you place i++/++i in loop condition it is same as while loop, but if you place in increment expression, it is calculated after the loop body & so whether it is i++ or ++i doesn't make a difference.
Whenever you see a for loop change it to its equivalent while loop & you will be clear how it works.
Hope that helps !!

--Shweta<br />SCJP 1.4 <br />SCWCD
I agree. Here's the link:
subject: i++ and - -i
jQuery in Action, 3rd edition