Thursday, April 28, 2011

How is a for loop structured in Java?

Is it different than C or C#?

From stackoverflow
  • Check this link for yourself.

  • 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

    indyK1ng : +1 for demonstrating instead of just linking
    MattC : 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.
    Gavin Miller : @MattC - Didn't write it, just grabbed it from the website referenced.
  • 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

    dfa : IIRC C99 allows declarations like this: for (int i = ... )
  • 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".

0 comments:

Post a Comment