MOCKSTACKS
EN
Questions And Answers

More Tutorials









Java For Each Loop


For each loop is an enhanced version of for loop.
It travels each element of the data structure one by one.
Note that you can not skip any element in for loop and it is also not possible to traverse elements in reverse order with the help of for each loop.
It increases the readability of the code.
If you just want to simply traverse an array from start to end then it is recommended to use for each loop.

Syntax :

/* for (int element:Arr) {
            Sout(element);    //Prints all the elements
} */

Example :


class CWH_forEachLoop{  
  public static void main(String args[]){  
   //declaring an array  
   int arr[]={1,2,3,3,4,5};  
   //traversing the array with for-each loop  
   for(int i:arr){  
     System.out.println(i);  
   }  
 }   
}  

Output

1
2
3
4
5

Example


package com.company;

public class cwh_27_arrays {
    public static void main(String[] args) {


        int [] marks = {98, 45, 79, 99, 80};
        // System.out.println(marks.length);

        // Displaying the Array (Naive way)
        System.out.println("Printing using Naive way");
        System.out.println(marks[0]);
        System.out.println(marks[1]);
        System.out.println(marks[2]);
        System.out.println(marks[3]);
        System.out.println(marks[4]);

        // Displaying the Array (for loop)
        System.out.println("Printing using for loop");
        for(int i=0;i<marks.length;i++){
            System.out.println(marks[i]);
        }
    }
}

Output

Printing using Naive way
98
45
79
99
80
Printing using for loop
98
45
79
99
80


Conclusion

In this page (written and validated by ) you learned about Java For Each Loop . What's Next? If you are interested in completing Java tutorial, your next topic will be learning about: Java Multidimensional Arrays.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.