Use a foreach(for each) style for loop. : Foreach « Language Basics « Java






Use a foreach(for each) style for loop.

Use a foreach(for each) style for loop.

public class ForEach {  
  public static void main(String args[]) {  
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  
    int sum = 0;  
 
    // use for-each style for to display and sum the values 
    for(int x : nums) {  
      System.out.println("Value is: " + x); 
      sum += x;  
    }  
 
    System.out.println("Summation: " + sum); 
  }  
}


           
       








Related examples in the same category

1.Foreach ArrayForeach Array
2.Simple demo to print all the types of an enumSimple demo to print all the types of an enum
3.Foreach and generic data structureForeach and generic data structure
4.Use break with a foreach(for each) style for.Use break with a foreach(for each) style for.
5.The foreach(for each) loop is essentially read-only.
6.Use foreach(for each) style for on a two-dimensional array.
7.Search an array using foreach(for each) style for.
8.Using a foreach(for each) for loop with a collection.
9.Using a foreach(for each) for loop on an Iterable object.
10.Java for In(forin) TesterJava for In(forin)  Tester
11.Java for in (forin) with CollectionJava for in (forin) with Collection
12.Java for in (forin) with generic CollectionJava for in (forin) with generic Collection
13.Java for in (forin): line-by-line iteration through a text fileJava for in (forin): line-by-line iteration through a text file