For-Each Loop

Why is the output 81.37? Shouldn’t it be the first element in the array list?

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile: For-Each Loops

Could you explain why you believe it should?

From my understanding, the for-each loop iterates through each element in the array list beginning with the first one which is 74.66 ie (expenses.get(0)). So shouldn’t it print the 0th index?

Could you paste your code in a reply?

import java.util.ArrayList;

class MostExpensive {

public static void main(String args) {

ArrayList<Double> expenses = new ArrayList<Double>();
expenses.add(74.46);
expenses.add(63.99);
expenses.add(10.57);
expenses.add(81.37);

double mostExpensive = 0;

// Iterate over expenses
for(double expense : expenses){

if (expense > mostExpensive){
mostExpensive = expense;
}
}

System.out.println(mostExpensive);

}

}

The above code is inside your for-each loop.

As you’ve said,

So the if statement is executed once for each element in the list. After the iteration is complete, the value mostExpensive is assigned to is printed. That value should be 81.37.

Printing the values inside the loop may help you to visualize what is happening. Try:

import java.util.ArrayList;

class MostExpensive {

  public static void main(String args) {

    ArrayList<Double> expenses = new ArrayList<Double>();
    expenses.add(74.46);
    expenses.add(63.99);
    expenses.add(10.57);
    expenses.add(81.37);

    double mostExpensive = 0;

    // Iterate over expenses
    for(double expense : expenses){
      // see what is being compared
      System.out.println("expense: " + expense + "  mostExpensive: " + mostExpensive);
      if (expense > mostExpensive){
        mostExpensive = expense;
        // Let's also see the value mostExpensive has been assigned to after the assignment
        System.out.println("mostExpensive (after update): " + mostExpensive);
      }
    }

    System.out.println(mostExpensive);

  }

}
2 Likes

This makes sense. It goes through each value checking the boolean condition for each iteration and since the last value is true it assigns it to the variable. Since it is the last iteration and it also meets the condition it is the one that gets assigned. Essentially, mostExpensive is reassigned 4 times with the last time being the final value. Thank you for your explanation.

1 Like