Null Handling in Java: Explanation & Practice

Handle NullPointerException gracefully

Problem summary

Write code that handles potential null values without crashing.

Starter code

public class Main {
    public static void main(String[] args) {
        String text = null; // Test case 1
        
        // Safely get length of text
        // Print length or "null" message
    }
}

Expected output and test cases

  • Handle null
    Text is null
  • Valid string
    Length: 5
  • Empty string
    Length: 0

Hints

  1. Check for null before using
  2. Or use try-catch for NPE
  3. Consider Optional for cleaner code

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler