1For(<DataType of array/List><Temp variable name> : <Array/List to be iterated>){
2 System.out.println();
3//Any other operation can be done with this temp variable.
4}
1
2public class HelloWorld {
3 public static void main(String[] args) {
4
5 // init array
6 String[] family = new String[] {"Member1", "Member2", "Member3", "Member4", "Member5"};
7
8 // print array
9 for(String name : family)
10 {
11 System.out.println(name);
12 }
13
14
15 }
16}
17
1import java.util.*;
2
3public class HelloWorld {
4 public static void main(String[] args) {
5
6 // you can define the type of list you want to init - String int etc inside <yourType> eg. <String>
7 List<String> family = new ArrayList();
8
9 family.add("Member1");
10 family.add("Member2");
11 family.add("Member3");
12 family.add("Member4");
13 family.add("Member5");
14
15 // print array
16 for(String name : family)
17 {
18 System.out.println(name);
19 }
20
21
22 }
23}
24
1 Scanner scanner = new Scanner( System.in );
2 int n = scanner.nextInt();
3 int[] a=new int[ n + 1 ];
4 for( int k = 1; k <= n; k ++ ){
5 a[ k ] = scanner.nextInt();
6 }
7 Arrays.sort( a );
8 for( int k = 1; k <= n; k ++ ){
9 System.out.print( a[k] + " " );
10 }
1// Java program to iterate over an array
2// using for loop
3import java.io.*;
4class GFG {
5
6 public static void main(String args[]) throws IOException
7 {
8 int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
9 int i, x;
10
11 // iterating over an array
12 for (i = 0; i < ar.length; i++) {
13
14 // accessing each element of array
15 x = ar[i];
16 System.out.print(x + " ");
17 }
18 }
19}
1class LoopThroughArray {
2 public static void main(String[] args)
3 {
4
5 int[] myArr = {1, 2, 3, 4};
6
7 for(int i : myArr){
8
9 System.out.println(i + "\n")
10
11 }
12
13 /* Output:
14 1
15 2
16 3
17 4
18 */
19
20 }
21}