16.5: Array Length
- Page ID
- 15260
The examples in the previous section only work if the array has three elements. It would be better to generalize the code to work with arrays of any size. We can do that by replacing the magic number, 3
, with a.length
:
double[] b = new double[a.length]; for (int i = 0; i < a.length; i++) { b[i] = a[i]; }
All arrays have a built-in constant, length
, that stores the number of elements. The expression a.length
may look like a method invocation, but there are no parentheses and no arguments.
The last time this loop gets executed, i
is a.length - 1
, which is the index of the last element. When i
is equal to a.length
, the condition fails and the body is not executed – which is a good thing, because trying to access a[a.length]
would throw an exception.
You can also use a.length
with Arrays.copyOf
:
double[] b = Arrays.copyOf(a, a.length);