java for item in array

h‮//:sptt‬www.lautturi.com
java for item in array

To iterate over the items in an array in Java, you can use a for loop.

Here's an example of how to do it:

public class Main {
  public static void main(String[] args) {
    int[] array = {1, 2, 3, 4, 5};

    // Iterate over the items in the array
    for (int i = 0; i < array.length; i++) {
      int item = array[i];
      System.out.println(item);
    }
  }
}

This code creates an array of integers and then uses a for loop to iterate over the items in the array. The loop starts at index 0 and continues until it reaches the end of the array, which is determined by the array.length property. The loop variable i is used to access the current item in the array.

You can use a similar approach to iterate over the items in an array of any type of data.

Alternatively, you can use the for-each loop, which allows you to iterate over the items in an array without explicitly specifying the loop variable and the loop condition:

public class Main {
  public static void main(String[] args) {
    int[] array = {1, 2, 3, 4, 5};

    // Iterate over the items in the array
    for (int item : array) {
      System.out.println(item);
    }
  }
}

The for-each loop is a convenient way to iterate over the items in an array, but it does not provide access to the index of each item. If you need to access the index as well as the value of each item, you will need to use the for loop as shown in the first example.

Created Time:2017-11-03 15:57:14  Author:lautturi