1

Is it different than C or C#?

3 Answers 3

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".

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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 - Didn't write it, just grabbed it from the website referenced.
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

1 Comment

IIRC C99 allows declarations like this: for (int i = ... )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.