I’ve been learning Java for a while and I’ve run into a problem I can’t figure out. I am currently learning arrays and how to iterate through them using loops. I generally understand how the if statement and the for loop work, but in this case I don’t understand the principle of this loop in combination with if statements. This is the example I’m talking about:
class MinMax { public static void main(String[] args) { int nums[] = new int[10]; int min, max; nums[0] = 99; nums[1] = -10; nums[2] = 100123; nums[3] = 18; nums[4] = -978; nums[5] = 5623; nums[6] = 463; nums[7] = -9; nums[8] = 287; nums[9] = 49; min = max = nums[0]; for (int i = 1; i < 10 ; i++){ if (nums[i] < min) min = nums[i]; if (nums[i] > max) max = nums[i]; } System.out.println("Largest and smallest value: " + min + " " + max); } }
I want to focus on this part:
min = max = nums[0]; for (int i = 1; i < 10 ; i++){ if (nums[i] < min) min = nums[i]; if (nums[i] > max) max = nums[i];
The only thing I understand from this is how this for loop works, but the instruction min = max = nums[0];
is unclear to me. Why are we assigning these values to each other? Probably because I don’t understand this instruction I also can’t understand the principle of if statements in this example.
Can someone explain it to me step by step please?
Advertisement
Answer
min = max = nums[0];
is simply a short way of writing
min = nums[0]; max = nums[0];
because the “value” of an assignment is equal to the value being assigned. Which means that max = nums[0]
evaluates to the same value as nums[0]
. So the line of code could be rewritten like this to make the meaning slightly more obvious:
min = (max = nums[0]);
And why this is done is simple: the “current minimum” and “current maximum” is often set to the first value of a non-empty list before the loop, because we know that the true minimum is at most as much as the value of the first element and the true maximum is at least as much as the value of the first element.