Bird
0
0

Find the problem in this Java program snippet:

medium📝 Debug Q7 of 15
Java - Command Line Arguments
Find the problem in this Java program snippet:

public class Sample {
  public static void main(String[] args) {
    for(int i=1; i<=args.length; i++) {
      System.out.println(args[i]);
    }
  }
}
ANo problem, code runs fine
BLoop index should start at 0, not 1
CSystem.out.println cannot print args[i]
Dargs.length should be args.size()
Step-by-Step Solution
Solution:
  1. Step 1: Understand array indexing in Java

    Arrays start at index 0, so loop should start at 0 to access first element.
  2. Step 2: Check loop bounds

    Loop runs i from 1 to args.length inclusive, causing ArrayIndexOutOfBoundsException at last iteration.
  3. Final Answer:

    Loop index should start at 0, not 1 -> Option B
  4. Quick Check:

    Array indexing starts at 0 in Java [OK]
Quick Trick: Array indexes start at 0, loops must reflect that [OK]
Common Mistakes:
  • Starting loop at 1
  • Using args.size() instead of length
  • Assuming print can't handle args[i]

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes