A NullPointerException (NPE) is a runtime exception in Java that occurs when your program attempts to use an object reference that has not been initialized (i.e., it points to null). This exception occurs when you try to perform actions on a 'null' object, such as:
1. Uninitialized Object References: String str = null; int length = str.length(); 2. Return Values from Methods String str = getNullString(); int length = str.length(); 3. Arrays int[] array = null; int length = array.length; 4. Collections List<String> list = null; list.add("test");
String str = "Hello, World!"; int length = str.length(); // Safe to use
if (str != null) { int length = str.length(); }
String str = (possiblyNullString != null) ? possiblyNullString: ""; int length = str.length();
Optional<String> optionalStr = Optional.ofNullable(possiblyNullString); optionalStr.ifPresent(s -> System.out.println(s.length()));
String str = Objects.requireNonNull(possiblyNullString, "String can't be null"); int length = str.length();
A ‘NullPointerException’ is a common runtime exception in Java that can be prevented through careful coding practices. By ensuring proper object initialization, performing null checks, using default values, leveraging the Optional class, and utilizing Objects.requireNonNull, developers can effectively avoid and handle ‘NullPointerException’, leading to more robust and reliable code.