Multiple choice technology programming languages

Given a one dimensional array arr, what is the correct way of getting the number of elements in arr.

  1. arr.length() – 1

  2. arr.length()

  3. arr.length - 1

  4. arr.length

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

The correct way of getting the number of elements in a one-dimensional array is:

A. arr.length

The option A, arr.length, returns the length of the array, which represents the number of elements in the array. This is the correct way to get the number of elements in the array.

The other options are incorrect:

B. arr.length() – 1: This option subtracts 1 from the length of the array, which does not give the correct count of elements in the array.

C. arr.length(): Adding parentheses after length is not necessary and will result in a syntax error.

D. arr.length - 1: This option subtracts 1 from the length of the array, which does not give the correct count of elements in the array.

So, the correct answer is: A. arr.length

AI explanation

For a Java array, the number of elements is obtained via the length field, accessed as arr.length (no parentheses) — length is a public final field on array objects, not a method. So "arr.length" is correct. "arr.length()" and "arr.length() – 1" are wrong because they treat length as a method call, which doesn't compile for arrays (String and List use .length()/.size() methods, but arrays don't). "arr.length - 1" gives the highest valid index, not the count of elements — off by one from what was asked. Only arr.length correctly returns the total number of elements in a one-dimensional array.