By utilizing for-each loops, the indices of a list are entirely abstracted away. However, in certain cases, it becomes necessary to know an element's index. In these scenarios, we can implement a traditional for loop. This loop has three parts which are separated by a semicolon.
for ( <initializationStatement>; <conditionalStatement>; <advancementStatement>) { // action to perform }
Let's look at a concrete example:
Integer sum = 0; for ( Integer i = 0; i < 4; i++) { sum += 2; }
This example is a little silly, but it demonstrates the concept. We declare and initialize a control variable, named i
to facilitate the iteration process. The loop body will execute only if the conditional statement is true. In our scenario, the conditional check is i < 4
. After each loop iteration, the advancement statement runs and increments i
by 1.
This means i
begins at 0, increments to 1, 2, and then 3. Once i
reaches 4, it is no longer less than 4, and the conditional statement evaluates to false, causing the loop to exit.
The code within the loop body executes every time the condition is true. As a result, sum
first equals 2, then 4, then 6, and finally 8.
For a practical use of traditional for loops let's add a twist to calculateSum()
. We'll update the method to compute the sum of all elements except the first element, which is stored in the 0th index of the list.
To achieve this, we must keep track of the index being iterated upon and skip the calculation on the 0th index. We'll use i
to keep track of the indices.
// The 0th index, element "1" shouldn't be summed! Integer[] numbersToSum = new Integer[] {1, 10, 2, 3}; Integer sumOfIntegers = calculateSum(numbersToSum); // sumOfIntegers will be 15 public Integer calculateSum(Integer[] numbers){ Integer sum = 0; for(Integer i = 0; i < numbers.size(); i++){ if(i != 0){ sum += numbers[i]; } } return sum; }
A lot just happened. The local variable i
represents the index and facilitates access to numbers
's elements. To support this, the conditional statement is updated so that i
never exceeds the size of the list. i
will be initialized to 0 and incremented all the way to 3 which prevents an out-of-bounds exception and ensures each element of the list is accessed once.
The loop will iterate four times. During each iteration, if the current index, i
, is not zero, then the summation logic is executed. This effectively excludes the 0th index from the calculation and achieves the intended outcome.