Is it different than C or C#?
+3
A:
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
2009-08-06 22:52:06
+1 for demonstrating instead of just linking
indyK1ng
2009-08-06 22:52:36
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
2009-08-06 23:20:26
@MattC - Didn't write it, just grabbed it from the website referenced.
Gavin Miller
2009-08-07 13:57:33
+1
A:
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
2009-08-06 22:52:31
+14
A:
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".
dfa
2009-08-06 22:52:31