You are here

Enhanced for loop java

Enhanced for loop java: Enhanced for loop is useful when scanning the array instead of using for loop. Syntax of enhanced for loop is:
for (data_type variable: array_name)
Here array_name is the name of array.

Java enhanced for loop integer array

  1. class EnhancedForLoop {
  2.   public static void main(String[] args) {
  3.     int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
  4.  
  5.     for (int t: primes) {
  6.       System.out.println(t);
  7.     }
  8.   }
  9. }

Download Enhanced for loop program.

Output of program:
Enhanced for loop java program

Java enhanced for loop strings

  1. class EnhancedForLoop {
  2.   public static void main(String[] args) {
  3.     String languages[] = { "C", "C++", "Java", "Python", "Ruby"};
  4.  
  5.     for (String sample: languages) {
  6.       System.out.println(sample);
  7.     }
  8.   }
  9. }