Visit a shared box twice

A Java warehouse program processes an array whose first and last positions refer to the same Box. Both loops visit positions from index zero to index two. What final value is stored in total? Answer in units as an exact integer.


Java
class Box {
    int units;
    Box(int units) {
        this.units = units;
    }
}

Box shared = new Box(10);
Box[] route = {shared, new Box(7), shared};

for (Box box : route) {
    if (box.units >= 8) {
        box.units -= 2;
    }
}

int total = 0;
for (Box box : route) {
    total += box.units;
}

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Arrays of Objects Questions: