The array numbers has 4 elements: 5, 10, 15, and 20.
Step 2: Use the length property
numbers.length returns the number of elements, which is 4.
Final Answer:
4 -> Option A
Quick Check:
Array length = 4 elements [OK]
Hint: Count elements, length equals that number [OK]
Common Mistakes:
Counting indexes instead of elements
Expecting length() method call
Thinking length includes extra space
4. Identify the error in this Java code snippet:
int[] data = new int[5];
System.out.println(data.length());
medium
A. Array length property does not exist in Java
B. Array size must be declared with curly braces, not square brackets
C. The array must be initialized with values before accessing length
D. Array length is accessed with parentheses, causing a compile error
Solution
Step 1: Check how length is accessed
The code uses data.length() with parentheses, but length is a property, not a method.
Step 2: Confirm correct syntax
The correct way is data.length without parentheses. Using parentheses causes a compile-time error.
Final Answer:
Array length is accessed with parentheses, causing a compile error -> Option D
Quick Check:
length is a property, no parentheses [OK]
Hint: Remember: length is property, no () [OK]
Common Mistakes:
Using parentheses after length
Confusing array initialization syntax
Thinking length needs array values first
5. Given the array int[] values = {2, 4, 6, 8, 10};, which code snippet correctly prints all elements using the array's length property?
hard
A. for (int i = 0; i <= values.length; i++) { System.out.println(values[i]); }
B. for (int i = 0; i < values.length; i++) { System.out.println(values[i]); }
C. for (int i = 1; i < values.length; i++) { System.out.println(values[i]); }
D. for (int i = 1; i <= values.length; i++) { System.out.println(values[i]); }
Solution
Step 1: Understand array indexing and length
Array indexes start at 0 and go up to length - 1. So valid indexes are 0 to 4 for this array.
Step 2: Analyze each loop condition
for (int i = 0; i <= values.length; i++) { System.out.println(values[i]); } uses i <= values.length, which tries to access index 5 (out of bounds). Options B and C start at 1, skipping the first element. for (int i = 0; i < values.length; i++) { System.out.println(values[i]); } correctly loops from 0 to 4.
Final Answer:
for (int i = 0; i < values.length; i++) { System.out.println(values[i]); } -> Option B
Quick Check:
Loop from 0 to length-1 to access all elements [OK]
Hint: Loop: i from 0 to length-1, use < i not <= [OK]
Common Mistakes:
Using <= length causing index out of bounds
Starting loop at 1 skipping first element
Confusing length with last index
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.