Wednesday, 23 November 2016

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

No comments:

Post a Comment