Try it here
Subscribe
Iterate Array in Java

Use of for loops to iterate Array in Java

use_of_for_loops_to_iterate_array_in_java

Use of for loops to iterate Array in Java You can iterate a array in Java using for loop.

There are two ways to do that.

  1. Using conventional approach of the "for" loop:

    Consider a String array array initialized as follows:

    String[] array= {"One", "Two", "Three", "Four", "Five"};

    Now iterate using counter and use of it as the index for the array.

    for(int i = 0; i< array.length; i++){
    
    System.out.println(array[i]);
    
    }
  2. Using foreach loop:

    Java provides a way to use the "for" loop that will iterate through each element of the array.Below is the example of it.

    for (String strTemp : array){
    
    System.out.println(strTemp);
    
    }

    You can see the difference between the loops. The code has reduced significantly. Also, there is no use of the index or rather the counter in the loop.

    Note -Do ensure that, the data type declared in the foreach loop must match the data type of the array/list that you are iterating.

foreach optimizes your loops, saves some typing and of course your time.

Writer profile pic

Arun on Mar 28, 2015 at 12:03 am


This article is contributed by Arun. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

WEB TECHNOLOGY
×

Forgot Password

Please enter your email address below and we will send you information to change your password.