Find the first matching ticket

A Java ticket system uses the following method to search an array. Each Ticket has an integer field code, and its constructor sets that field to the supplied value.


Java
static int indexOf(Ticket[] items, int target) {
    for (int i = 0; i < items.length; i++) {
        if (items[i] != null && items[i].code == target) {
            return i;
        }
    }
    return -1;
}


The array supplied to every call is initialized as follows:


Java
Ticket[] items = {
    new Ticket(17), new Ticket(58), null,
    new Ticket(41), new Ticket(58)
};


An object array has five indexed slots and references four Ticket objects.


Complete the table for three independent calls. Count a code comparison only when items[i].code == target is evaluated. Java evaluates the right side of && only when its left side is true. Give every answer as an exact integer.

Target codeReturned indexCode comparisons
41
58
99

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: