Challenge - 5 Problems
Array Length Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Java code using array length?
Consider the following Java code snippet. What will be printed when it runs?
Java
public class Main { public static void main(String[] args) { int[] numbers = {5, 10, 15, 20, 25}; System.out.println(numbers.length); } }
Attempts:
2 left
💡 Hint
Remember that the length property of an array gives the number of elements it contains.
✗ Incorrect
The array 'numbers' has 5 elements, so numbers.length returns 5.
❓ Predict Output
intermediateWhat is the output when accessing length of a multidimensional array?
Look at this Java code. What will it print?
Java
public class Main { public static void main(String[] args) { int[][] matrix = new int[3][4]; System.out.println(matrix.length); } }
Attempts:
2 left
💡 Hint
The length property on a 2D array returns the number of rows.
✗ Incorrect
The 'matrix' has 3 rows, so matrix.length is 3.
❓ Predict Output
advancedWhat happens if you try to assign to the length property of an array?
What will happen when this Java code runs?
Java
public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3}; arr.length = 5; System.out.println(arr.length); } }
Attempts:
2 left
💡 Hint
The length property of an array is final and cannot be changed.
✗ Incorrect
In Java, the length property of an array is final and cannot be assigned a new value, causing a compilation error.
❓ Predict Output
advancedWhat is the output of this code accessing length of a null array?
What will this Java program print or do?
Java
public class Main { public static void main(String[] args) { int[] arr = null; System.out.println(arr.length); } }
Attempts:
2 left
💡 Hint
Accessing a property on a null reference causes an error at runtime.
✗ Incorrect
Since arr is null, accessing arr.length causes a NullPointerException at runtime.
🧠 Conceptual
expertHow many elements are in the array after this code runs?
What is the number of elements in the array 'data' after executing this code?
Java
public class Main { public static void main(String[] args) { int[] data = new int[10]; data = new int[5]; System.out.println(data.length); } }
Attempts:
2 left
💡 Hint
The variable 'data' is reassigned to a new array before printing length.
✗ Incorrect
The original array of length 10 is replaced by a new array of length 5, so data.length is 5.
