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
- Check for null before using
- Or use try-catch for NPE
- Consider Optional for cleaner code
Related Exception Handling exercises
- Practice Age Range Validator in Java
- Practice Password Validation in Java
- Practice Resource Cleanup Pattern in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler