File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Question regarding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question regarding "for" loops" Watch "Question regarding "for" loops" New topic
Author

Question regarding "for" loops

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
Whether I say „j++“ or „++j“ in the for-loop j is always increased after the loop is
finished. WHY?
Why is it the same to say „i++“ or „++i“ in the loop? The result is always that „i“
is increased ? WHY?


C:\Java\EigeneJavaProgramme>java Skip1
LOOP 1 0
LOOP 2 1
LOOP 3 2
LOOP 4 3
LOOP 5 4
LOOP 6 5
LOOP 7 6
LOOP 8 7
LOOP 9 8
LOOP 10 9
END 10 10



C:\Java\EigeneJavaProgramme>java Skip1a
LOOP 1 0
LOOP 2 1
LOOP 3 2
LOOP 4 3
LOOP 5 4
LOOP 6 5
LOOP 7 6
LOOP 8 7
LOOP 9 8
LOOP 10 9
END 10 10
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Because that is what both the pre-increment and post-increment operator do - incrementing the variable. The only difference between them is the *value of the expression*.
The following code should make that clear:

Did that help?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Whether I say �j++� or �++j� in the for-loop j is always increased after the loop is
finished. WHY?

Because that's how for-loops in Java work. First the declaration/initialization part is performed. Then the test is performed. If the test returns true, then the loop body is executed with the current value(s) of any identifiers declared/used in the initialization and increment sections of the for-loop declaration. Then any statements in the increment section of the loop declaration are performed. These statements typically increment some variable or otherwise cause the loop to get closer to termination. These statements are each executed in isolation any other statement. Then the test is performed again and the process repeats as necessary.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question regarding "for" loops