Handling NullPointerException Example
This program demonstrates handling NullPointerException.
Problem Statement
Write a Java program that handles null object access using try-catch.
Source Code
| 1 | public class NullPointerExceptionExample { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq NullPointerException Example"); |
| 4 | try { |
| 5 | String s=null; |
| 6 | System.out.println(s.length()); |
| 7 | } catch(NullPointerException e) { |
| 8 | System.out.println("Eduinq Exception: Null Object Access"); |
| 9 | } |
| 10 | } |
| 11 | } |
Program Output
Eduinq NullPointerException Example Eduinq Exception: Null Object Access
Explanation
NullPointerException occurs when accessing methods on null objects. - Try-catch prevents program crash and provides user-friendly error message. - This design improves reliability and error handling. - In enterprise systems, null checks are critical for stability and avoiding runtime failures. Conclusion: Shows handling of NullPointerException.