Java's for-each loop demo

The for-each loop introduced in Java5 (also called the "enhanced for loop"). 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. The syntax of for-each loop is given below:
for(data_type  variable  :  array  |  collection){  }  

For example, consider the code
int arr[ ]={1,2,3,4};

for(int  i : arr) {
     System.out.println(i);
}  

The output of this will be
1
2
3
4

PROGRAM
class ForEachDemo {

 public static void main(String[] args) {
  
  String str[ ] = {"Physics", "Chemistry", "Maths"}; 
  
  for(String a : str) {
   
   System.out.println(a);
  }
 }
}
OUTPUT
C:\>javac ForEachDemo.java
C:\>java PForEachDemo
Physics
Chemistry
Maths

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative