tags:

views:

452

answers:

4

Is it different than C or C#?

A: 

Check this link for yourself.

stanigator
+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
+1 for demonstrating instead of just linking
indyK1ng
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
@MattC - Didn't write it, just grabbed it from the website referenced.
Gavin Miller
+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
IIRC C99 allows declarations like this: for (int i = ... )
dfa
+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