Five Ways to Loop Through An Array in Java



This site utilizes Google Analytics, Google AdSense, as well as participates in affiliate partnerships with various companies including Amazon. Please view the privacy policy for more details.

It’s been a little while since I wrote something Java-related (March 28, 2019 was the last time, to be exact) so I figured I write something simple.

Hence Five Ways to Loop Through An Array in Java.

An array is one of the most basic data structures in programming. It’s essentially a fixed-length list of similar items (referred to as elements) that are often accessed via their index. The index is simply their position in the array, starting with position zero.

One of the benefits of an array is the ability to loop through each element and process some sort of work on the element.

Looping through an array is often called iterating through or iterating over the array.

Since I’m a Java developer, I present to the world Five Ways to Loop Through An Array in Java.

For the purpose of this exercise, I’ll loop through the following String array:

String[] strings = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};

And, because I actually want to do some work, each iteration of the loop will call the following method:

private void doTheThing(final String string) {
    System.out.println(string);
}

While loop

Using a while loop to iterate over an array isn’t the cleanest way to do so, but it is possible:

int i = 0;

while(wi < strings.length) {
    doTheThing(strings[wi]);
    i++;
}

For Loop

for(int i = 0; i < strings.length; i++) {
    doTheThing(strings[i]);
}

Enhanced For Loop

The Enhanced For Loop (sometimes also called a foreach loop) was introduced in Java 5. With the enhanced for loop, you no longer have to keep track of the index (the int i in the previous two examples). This improves readability.

The Enhanced For Loop’s strength is also its weakness. With no access to the index, you can’t peak at the next item (e.g. strings[i+1]) or look at the previous item (e.g. strings[i-1]). Thankfully this isn’t always needed.

for(final String string : strings) {
    doTheThing(string);
}

Stream

Java 8 introduced functional programming aided by lamdas and streams.

Arrays by themselves are not streams, but they can be easily used by streams by calling Arrays.stream:

Arrays.stream(strings).forEach(this::doTheThing);

You can also use Stream.of, but it immediately calls Arrays.stream:

Stream.of(strings).forEach(this::doTheThing);

Here’s the Java code for Stream.of, showing that it just calls Arrays.stream:

    /**
     * Returns a sequential ordered stream whose elements are the specified values.
     *
     * @param <T> the type of stream elements
     * @param values the elements of the new stream
     * @return the new stream
     */
    @SafeVarargs
    @SuppressWarnings("varargs") // Creating a stream from an array is safe
    public static<T> Stream<T> of(T... values) {
        return Arrays.stream(values);
    }

Recursively

For fun, here’s a recursive way to loop through arrays. Don’t do this except as an intellectual exercise:

private void loop(final String[] strings, final int i) {
    if(i < strings.length) {
        doTheThing(strings[i]);
        loop(strings, i + 1);
    }
}

Start the recursive loop by calling the method with the array and the number zero:

loop(strings, 0);

The End

3 comments for Five Ways to Loop Through An Array in Java

  • avatar for n/a n/a

    Hello Sir i can’t seem to get a simple loop to run.

    It only prints the first index of my array.

    I’ve managed to create a program where i copy paste a text into a text area, split it, and display what ever index I need on the console,

    but i need to go further.

    ex.

     text(via TextArea): hgyt jfur kdie
     String text = TextArea.getText();
     String[] textsplit = text.split(" \\s{0,}+");
    

    yields the following array when printed.

     [ hgyt , jfur, kdie ] = textsplit
    

    now I need to split further…

     [ [h,g,y,t] , [j,f,u,r], [k,d,i,e] ]
    

    I’ve tried building an array of arrays, switch statements, not just ‘for’ loops, the simplest ‘for’ loop only prints the first index.

     for (int i = 0; i< textsplit.length;)
     {
     String line =(textsplit[i]);
     
     String[] linesplit= line.split("");
     String Kline = Arrays.toString(linesplit);
     System.out.println(line );
     System.out.println(Kline )
     
     ;break;
     
     }//ENDOF for loop
    

    output:

     hgyt
     [h,g,y,t]
    

    I almost does what i need, but not completely.

    The following code is interesting but cannot extract strings from the copy/pasted text in the final result, merely an attempt to construct a multiArray from variables generated by the copied text.

     for (int i = 0; i< textsplit.length;)
     {
     String line =(textsplit[i]);
     
     String[] linesplit= line.split("");
     String Kline = Arrays.toString(linesplit);
     System.out.println(line );
     System.out.println(Kline )
     
     int x= textsplit.length;
     int y = linesplit.length;
     String[][] sort = new String[x][y];
     String sorted = Arrays.toString(sort);
     System.out.println(sorted);
     String[] reduce = sorted.split(",");
     String fin = Arrays.toString(reduce);
     System.out.println(String.valueOf(sort));
     System.out.println(String.valueOf(fin));
     
     break;
     }//ENDOF for loop
    

    output:

     hgyt
     [h, g, y, t]
     [[Ljava.lang.String;@531e248f, [Ljava.lang.String;@4a6c9da, [Ljava.lang.String;@b45bde1]
     [[Ljava.lang.String;@64329de2
     [[[Ljava.lang.String;@531e248f,  [Ljava.lang.String;@4a6c9da,  [Ljava.lang.String;@b45bde1]]
    

    I believe these are addresses for and “empty” array.

    any advice would be great!

    • Why do you have a “break” at the end of your for-loops? Having that break ensures that the for-loop while loop at most once. Try removing it and you should get the result you want.

    • avatar for n/a n/a

      Thank You for Your response!

      While trying to figure this out. I found that the break stopped the loop. As without it, the loop would keep reiterating the first index. very strange.

      I’ve since found a solution. here it is.. I managed to figure it out using jdoodle. it’s not totally perfect as if prints each index twice after the the first loop. but it does the job. disregard all the extra libraries. I’m juggling my main code between machines in and out of work haha.

      one again thanks o bunch.

       import java.awt.EventQueue;
       import java.util.ArrayList;
       import java.util.Arrays;
       import java.io.IOException;
       import java.io.IOException;
       import java.io.OutputStream;
       
       public class Main{
       
       public static void main(String []args){
       
       String text = "hgyt jfur kdie";
       
       String[] textarray = text.split(" \\s{0,}+");
       String showarray = Arrays.toString(textarray);
       System.out.println(showarray);System.out.println("");System.out.println("");
       System.out.println("for loop RESULT = ");
       
       for (int i = 0; i<= textarray.length;i++)
       {
       String line =(textarray[i]);
       String[] linesplit= line.split("");
       String Kline = Arrays.toString(linesplit);
       
       System.out.println(line );
       System.out.println(Kline );
       System.out.println("");
       
       while (i < textarray.length )
       {
       
       System.out.println(String.valueOf(textarray[i+1])); break; }//ENDOF while
       
       }//ENDOF for loop
       }//ENDOF main(String []args)
       }//ENDOFCLASS
      

      OUTPUT:

       [hgyt, jfur, kdie]
       
       for loop RESULT =
       hgyt
       [h, g, y, t]
       
       jfur
       jfur
       [j, f, u, r]
       
       kdie
       kdie
       [k, d, i, e]
       
       Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
       at Main.main(Main.java:49)
      

    Reply to This Thread

Leave a Reply

Note that comments won't appear until approved.