Is it different than C or C#?
Asked
Active
Viewed 881 times
3 Answers
14
Java has one keyword, for, but it can be used in two different manner:
/* classical, C/C++ school */
for (int i = 0; i < N; i++) {
}
for-each style:
// more object oriented, since you use implicitly an Iterator
// without exposing any representation details
for (String a : anyIterable) {
}
it works for any type that implements Iterable<String>
such as List<String>
, Set<String>
, etc.
The latter form works also for arrays, see this question for a more "phisophical approach".
3
The following demonstrates the syntax of a java for loop (from the for loop in Java):
class Hello {
public static void main (String args[]) {
System.out.print("Hello "); // Say Hello
for (int i = 0; i < args.length; i = i + 1) { // Test and Loop
System.out.print(args[i]);
System.out.print(" ");
}
System.out.println(); // Finish the line
}
}
Also see the Wiki entry on For loop

Gavin Miller
- 43,168
- 21
- 122
- 188
-
I'm interested why you did i = i + 1 instead of just i++. Was it just you being verbose or do you have another reason? I've just never seen that used in a very long time. – MattC Aug 06 '09 at 23:20
-
@MattC - Didn't write it, just grabbed it from the website referenced. – Gavin Miller Aug 07 '09 at 13:57
1
The only difference between java's for-loop syntax and C's is you can declare variables in the initialization field (1st section) of the loop

bkritzer
- 1,418
- 3
- 16
- 27