For Each In Java Example

Chapter: Control Statements Last Updated: 07-06-2017 16:05:17 UTC

Program:

            /* ............... START ............... */
                
public class JavaForEach {
	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);
	}
}
                /* ............... END ............... */
        

Output

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

Notes:

  • The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements.
  • The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Tags

For Each, Java

Similar Programs Chapter Last Updated
Java For Loop And ForEach Loop Example Control Statements 03-09-2016
Java Enum And Switch Statement Control Statements 03-09-2016
Control Statements In Java Example Control Statements 19-06-2016
If Statement In Java Example Control Statements 17-06-2016
Java Switch Example Control Statements 14-06-2016
While Loop In Java Example Control Statements 08-06-2017
Return Statement In Java example Control Statements 15-07-2016
Print Stars In Java Example Control Statements 15-07-2016
Nested Loop In Java Example Control Statements 15-07-2016
Infinite While Loop In Java Control Statements 10-06-2016
Infinite Loop In Java Example Control Statements 15-07-2016
If Else Statement In Java Example Control Statements 10-06-2016
For Loop In Java Example Control Statements 07-06-2017
Do While Loop In Java Example Control Statements 10-06-2016
Continue Statement In Java Example Control Statements 30-03-2017
Java Break Statement Example Control Statements 06-07-2016

1