The Enhanced for Loop with Arrays

The header
Four phones sit on a classroom shelf, and charge records each one's battery level in percent.
int[] charge = {80, 35, 100, 12};
int sum = 0;
for (int c : charge)
{
sum += c;
}
System.out.println(sum);
Its header reads "for each int c in charge". On successive passes c holds 80, 35, 100, and 12, so the segment prints 227. No index appears anywhere in it.
Assigning to the loop variable
An hour on the shelf's charger adds 15 percent to each phone, up to 100. The loop below is meant to record that.
for (int c : charge)
{
c = c + 15;
if (c > 100)
{
c = 100;
}
}
It compiles and runs, and charge still holds 80, 35, 100, and 12. On each pass c received a copy of an element. The assignments changed only the copy, and the copy was discarded when the pass ended.
In the indexed version, the left side of the assignment is charge[i], which is the array's own element, and the new value stays in it.
for (int i = 0; i < charge.length; i++)
{
charge[i] = charge[i] + 15;
if (charge[i] > 100)
{
charge[i] = 100;
}
}
Now the array holds 95, 50, 100, and 27.
Rewriting a loop
The sum at the top can be written with an index: sum += charge[i]; inside a loop whose i runs from 0 through charge.length - 1. A while loop works too, with the index declared above it. Each rewrite visits the same elements in the same order and does the same thing with each.
The other direction doesn't always work. Assigning to the loop variable can't change the array, so the charging loop needs charge[i]. That takes an index, or a counter kept beside an enhanced loop. An enhanced loop has no index of its own, so reporting where a value sits takes the same kind of counter.
Arrays of objects
A Phone class keeps its charge in an instance variable.
public class Phone
{
private int percent;
public Phone(int p)
{
percent = p;
}
public int getPercent()
{
return percent;
}
public void plugIn()
{
percent = 100;
}
}
Here the array holds references to Phone objects.
Phone[] shelf = {new Phone(80), new Phone(12)};
for (Phone p : shelf)
{
if (p.getPercent() < 20)
{
p.plugIn();
}
}
After the loop, shelf[1].getPercent() returns 100. The loop variable p receives the same reference the array element holds, so both lead to one Phone object, and plugIn changes that object. The references stored in shelf are the same ones after the loop as before; only the objects they lead to changed.