Bird
0
0

Why does the following code print 3 instead of 4?

hard📝 Conceptual Q10 of 15
Java - Arrays
Why does the following code print 3 instead of 4?
int[] arr = {1, 2, 3, 4};
for (int i = 0; i < arr.length - 1; i++) {
    System.out.println(arr[i]);
}
ABecause the last element is null and skipped
BBecause arrays start at index 1 in Java
CBecause the loop stops before the last element due to <code>arr.length - 1</code>
DBecause the loop condition is incorrect syntax
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop condition

    The loop runs while i < arr.length - 1, so it stops at index 2 (third element).
  2. Step 2: Understand why last element is skipped

    Since the condition excludes the last index, the element at index 3 is not printed.
  3. Final Answer:

    Because the loop stops before the last element due to arr.length - 1 -> Option C
  4. Quick Check:

    Loop condition excludes last index = prints 3 elements [OK]
Quick Trick: Loop with i < length - 1 excludes last element [OK]
Common Mistakes:
  • Thinking arrays start at 1
  • Assuming null elements
  • Confusing syntax error with logic error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes