Bird
0
0

What will be printed when the following Java code is executed?

medium📝 Predict Output Q4 of 15
Java - Exception Handling
What will be printed when the following Java code is executed?
public class Demo {
  public static void main(String[] args) {
    try {
      String s = null;
      System.out.println(s.length());
    } catch (NullPointerException e) {
      System.out.println("Null pointer caught");
    }
  }
}
A0
BNull pointer caught
CCompilation error
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Identify the exception

    Calling length() on a null string causes a NullPointerException.
  2. Step 2: Check the catch block

    The exception is caught by the catch (NullPointerException e) block, which prints "Null pointer caught".
  3. Final Answer:

    Null pointer caught -> Option B
  4. Quick Check:

    NullPointerException caught and handled [OK]
Quick Trick: NullPointerException triggers catch block [OK]
Common Mistakes:
  • Expecting a compilation error
  • Assuming null length returns 0
  • Ignoring exception handling

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes