Java OCA OCP Practice Question 571

Question

Which of the following references the first and last element in a non-empty array?

  • A. trains[0] and trains[trains.length]
  • B. trains[0] and trains[trains.length - 1]
  • C. trains[1] and trains[trains.length]
  • D. trains[1] and trains[trains.length - 1]


B.

Note

Array indices start with 0, making Options C and D incorrect.

The length attribute refers to the number of elements in an array.

It is one past the last valid array index. Therefore, Option B is correct.




PreviousNext

Related