Checking the Elements of an Array

At least one element
A radar sign records the speed of each car that passes it, in miles per hour, and the limit on that road is 35.
int[] speeds = {28, 33, 25, 41, 38};
Whether any car sped is a yes-or-no question about the whole array, so its answer goes in a boolean.
boolean anySpeeding = false;
for (int s : speeds)
{
if (s > 35)
{
anySpeeding = true;
}
}
The variable starts false, since no speeding car has been seen yet. The 41 sets it to true. Nothing in the loop sets it back, so it ends true.
A body of anySpeeding = s > 35; would be wrong, though. That statement replaces the answer on every pass. After the loop it would describe only the last car, and the 38 would make it true by luck.
Every element
Whether every car stayed under 45, ten over the limit, is a different kind of question. No single element can prove it, but a single element can disprove it.
boolean allUnder45 = true;
for (int s : speeds)
{
if (s >= 45)
{
allUnder45 = false;
}
}
The variable starts true, and the if looks for a counterexample. None of the five speeds is 45 or more, so it ends true.
Consecutive pairs
Two speeders in a row may mean a group of cars is racing. Comparing each element with the next one reads speeds[i + 1], so the largest i the loop may use is speeds.length - 2.
boolean twoInARow = false;
for (int i = 0; i < speeds.length - 1; i++)
{
if (speeds[i] > 35 && speeds[i + 1] > 35)
{
twoInARow = true;
}
}
Five speeds make four pairs. The last of them, 41 and 38, are both over 35, so twoInARow ends true. With i < speeds.length as the condition, the last pass would read speeds[5] and throw an ArrayIndexOutOfBoundsException.
Duplicates
Whether two cars had the same speed takes a loop inside a loop, since each element has to be compared with every element after it.
boolean repeat = false;
for (int i = 0; i < speeds.length - 1; i++)
{
for (int later = i + 1; later < speeds.length; later++)
{
if (speeds[i] == speeds[later])
{
repeat = true;
}
}
}
Starting later at i + 1 compares each pair of positions once and never compares an element with itself. Here no two of the five speeds match, so repeat stays false.
Returning early
Inside a method, a yes-or-no answer can be returned as soon as it's known.
public static boolean anyOver(int[] speeds, int limit)
{
for (int s : speeds)
{
if (s > limit)
{
return true;
}
}
return false;
}
The call anyOver(speeds, 35) returns true at the fourth element and never examines the fifth. The final return false; is reached only when no element was over the limit, because any element over it would have ended the method first.