A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/java/java_foreach_loop.htm below:

Java - for each Loop

Java - for each Loop Java for each Loop

A for each loop is a special repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times.

A for each loop is useful even when you do not know how many times a task is to be repeated.

Syntax

Following is the syntax of enhanced for loop (or, for each loop) −

for(declaration : expression) {
   // Statements
}
Execution Process Examples Example 1: Iterating Over a List of Integers

In this example, we're showing the use of a foreach loop to print contents of an List of Integers. Here we're creating an List of integers as numbers and initialized it some values. Then using foreach loop, each number is printed.

import java.util.Arrays;
import java.util.List;

public class Test {

   public static void main(String args[]) {
      List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);

      for(Integer x : numbers ) {
         System.out.print( x );
         System.out.print(",");
      }
   }
}
Output
10, 20, 30, 40, 50,
Example 2: Iterating Over a List of Strings

In this example, we're showing the use of a foreach loop to print contents of an List of String. Here we're creating an array of Strings as names and initialized it some values. Then using foreach loop, each name is printed.

import java.util.Arrays;
import java.util.List;

public class Test {

   public static void main(String args[]) {
      List<String> names = Arrays.asList("James", "Larry", "Tom", "Lacy");

      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}
Output
James, Larry, Tom, Lacy,
Example 3: Iterating Over an Array of Objects

In this example, we're showing the use of a foreach loop to print contents of an array of Student Object. Here we're creating an array of Students as Student object and initialized it some values. Then using foreach loop, each name is printed.

public class Test {

   public static void main(String args[]) {
      Student[] students = { new Student(1, "Julie"), new Student(3, "Adam"), new Student(2, "Robert") };

      for( Students student : students ) {
         System.out.print( student );
         System.out.print(",");
      }
   }
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}
Output
[ 1, Julie ],[ 3, Adam ],[ 2, Robert ],

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4