Cant understand For Each Loop

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;
for(double expense : expenses){
  if(expense>mostExpensive){
   mostExpensive=expense;
    } }
System.out.println(mostExpensive);I

if expense is one of the times of expenses and in the if statement every item is bigger than 0
Why mostExpensive=expensive means 81.37?

mostExpensive doesn’t stay zero, once the if condition is true, mostExpensive is set to new most expensive item.

it would look like this:

if (74.46 > 0) 

this is true, so most expensive is now set to 74.46, so for the next iteration of the loop the comparison looks like:

if (63.99 > 74.46)

this one is false, so mostExpensive isn’t updated.

and so forth, this way you end up with the most expensive item.

1 Like