Bird
0
0

Identify the error in the following Java code snippet:

medium📝 Debug Q6 of 15
Java - Memory Management Basics
Identify the error in the following Java code snippet:
public class Test {
  public static void main(String[] args) {
    String s;
    System.out.println(s.length());
  }
}
AString class does not have length() method
BVariable 's' is not initialized before use
CCannot print inside main method
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check variable declaration

    Variable 's' is declared but not initialized.
  2. Step 2: Analyze usage

    Calling s.length() on uninitialized variable causes compile-time error.
  3. Step 3: Confirm String methods

    String class has length() method, so String class does not have length() method is incorrect.
  4. Final Answer:

    Variable 's' is not initialized before use -> Option B
  5. Quick Check:

    Local variables must be initialized before use [OK]
Quick Trick: Initialize local variables before use [OK]
Common Mistakes:
  • Assuming default initialization for local variables
  • Confusing String length() with length field
  • Ignoring compile-time errors for uninitialized variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes