Length of Arrays - Quiz

Total: 5 questions

1. 

How do you get the length of an array in Java?

An array's length is stored in its public length field, accessed with a dot and without parentheses: array.length. An array is an object, and the JVM fills in its length at creation time. The value is set once and never changes. Note that length is a field, so writing it with parentheses, array.length(), will not compile.

2. 

Can you change the length of an array after it is created?

No. An array's length is fixed forever at creation time, and the length field is read-only — the assignment array.length = 10; does not compile. To get an array of a different size, create a new one and copy the elements, most conveniently with Arrays.copyOf(array, newLength). If the size has to change often, use an ArrayList, which resizes automatically and reports its size via the size() method.

3. 

What is the difference between length, length(), and size() in Java?

length is a field (no parentheses) that arrays have: array.length. length() is a method of strings: str.length() on String and StringBuilder. size() is a method of collections: list.size() on List, Set, and Map. Confusing the array field with the string method is one of the most common beginner mistakes and a popular interview question.

4. 

How do you get the total number of elements in a two-dimensional (including jagged) array?

A two-dimensional array in Java is an "array of arrays", so array.length only gives the number of rows, while array[i].length gives the length of a specific row. To get the total element count, sum the lengths of all rows: for (int[] row : array) total += row.length;. For a rectangular array you can multiply array.length by array[0].length, but for a jagged array, where rows have different lengths, that produces a wrong result.

5. 

What does reading length return for an empty array or a null reference?

For an empty array (new int[0]) the length field returns 0 — it is a valid zero-length object. If the reference is null, no array object exists, and reading length throws a NullPointerException. That is why arrays coming from external code are first checked for null and only then read: if (array != null && array.length > 0) { ... }. An empty array and null are fundamentally different things.

Page 1 of 1