Ria
Ria

Reputation: 3

For Loops and Arrays in Java

This is kind of a weird question. I hope it doesn’t sound too stupid but I always want to know why. I think I understand how you access an array with a for loop.

You start with i = 0 cause 0 is the first part of the array and the condition while i > array cause it can’t exceed the array and i++ to access the next part of the array.

But is there a specific reason why you have to use a for loop and is there any other way to read values from an array?

Edit: thanks to everyone who answered it was super helpful and I learned some new stuff

Upvotes: 0

Views: 6926

Answers (5)

DevilsHnd - 退した
DevilsHnd - 退した

Reputation: 9192

The better question might be: Why wouldn't you want to use a FOR loop to iterate through an array? There are many ways to iterate through an Array or a collection and there is no law that states you have to use the FOR loop. In a lot of cases, it's simply the best to use for speed, ease of use, and readability. And yet, in other cases it is not:

The Array:

int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Display Array with the typical for loop:

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

Display Array with the enhanced for loop:

for(Integer num : array) {
    System.out.println(num);
}

Display Array with the do/while loop:

int i = 0;
do {
    System.out.println(array[i++]);
} while (i < array.length);

Display Array with the while loop:

int j = 0;
while (j < array.length) {
    System.out.println(array[j++]);
}

Display Array through Recursive Iteration:

iterateArray(array, 0);  // 0 is the start index.


// The 'iterateArray()' method:
private static int iterateArray(int[] array, int index) {
    System.out.println(array[index]);
    index++; 
    if (index == array.length) {
        return 0;
    }
    return iterateArray(array,index);
}

Display Array using Arrays.stream() (Java8+):

Arrays.stream(array).forEach(e->System.out.print(e + System.lineSeparator())); 

Display Array using IntStream (Java8+):

IntStream.range(0, array.length).mapToObj(index -> array[index]).forEach(System.out::println);

Choose your desired weapon....

Upvotes: 3

Gaurav Pathak
Gaurav Pathak

Reputation: 2593

Considering you have an array like : 
int[] array = {1,2,4,5,6};

You can use stream to iterate over it, apart from printing you can perform lot many thing over this array.

Arrays.stream(array).forEach(System.out::println);

Similarly you can do lot many action over collections as well:

List<String> myList = new ArrayList<>(); List
myList.add("A");
myList.add("B");
    

Stream.of(myList).forEach(System.out::println);

myList.forEach(System.out::println);

Upvotes: 1

Itami
Itami

Reputation: 78

First I'm confuse by this statement

You start with i = 0 cause 0 is the first part of the array and the condition while i > array cause it can’t exceed the array and i++ to access the next part of the array.

because as I know, your i should always be less (<) than the length of the array to avoid ArrayIndexOutOfBoundsException.

And for the reason:

But is there a specific reason why you have to use a for loop and is there any other way to read values from an array?

Actually, you can use any loop that you know depending on what you need. But is is easier to use for each loop for most of the time. e.g.

int [] arrayNumber = new int[10]; // or some constant value if there is.
. . . . 
for(int number: arrayNumber){
   . . . . //any thing you want to do with the value of the array
}

This code will surely avoid ArrayIndexOutOfBoundsException because for each loop will make sure that it will only loop for the exact amount/length of the array. But the disadvantage of using this loop, you will loose track of the index (i) of the selected array. To work for this disadvantage, you will add new integer index(i) and set value to zero (0) int i = 0 out side the for each and adding increment inside the loop. Eg.

int i = 0;
for(int val: arrayVar){
    ....//do something here
    i++;
}

And doing this, will make the code harder to read than for loop that contains initialization of index (i), validation of value of i and increments of i all inside the for header. Eg.

for(int i = 0; i < arrayVar.length; i++ ){
    //do something here
}

For the difference of for and for each loop on array, see the selected answer here. First for is the for loop while the second loop on the answer is the for each loop

Hope this helps.

Upvotes: 0

aedan
aedan

Reputation: 217

Well, you don't need to loop if you only need 1 index and you know where it is. int[] myNum = {10, 20, 30, 40}; // then if you need to access 20 on index 1 myNum[1];

But if you need to access everything then yes, you iterate every index via loop (foreach, while, stream etc.)

Upvotes: 0

SoDamnMetal
SoDamnMetal

Reputation: 77

I'm pretty sure you can use any kind of loop to access an array. For loops are the standard because they're the easiest to read, write and understand at a glance.

Upvotes: 0

Related Questions