For-Each Loop

For-each Loop ( Java Exercise )

I’m trying to understand why this code outputs the highest value from the arrayList ( Check Below ) Yet from my understanding the variable mostExpensive of datatype double has been initialised at zero. Help! java beginner here!

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);

}

}

Hi,
This bit here is the key;

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

The for loop is assigning the value of each element in expenses to expense one at a time.
The code above then checks if that value is greater than the current value of mostExpensive.
If it is, then mostExpensive will be overwritten with that value.

i.e. on the first loop through, expense will be 74.46 and mostExpensive is 0.
expense is greater than mostExpensive (74.46 > 0), so mostExpensive will be changed to 74.46.
next time round, expense carries on through the array, and is changed to the next element, 63.99.
This is then checked with the current value of mostExpensive - which is now 74.46.
63.99 isn’t greater than 74.46, so mostExpensive doesn’t change this time and we continue to the next element, 10.57…

hope that helps

2 Likes

Hello there,

Thanks for that clarification…I now understand

1 Like