Kar

Kar started this conversation 3 months ago.

0

1

java

NullPointerException in Java – unexpected crashes on method calls or unboxing

My Java application throws NullPointerException in surprising places—when calling .length() on a string, unboxing Integer to int, or chaining method calls. Why does this happen and how can I avoid it?

Digiaru

Posted 3 months ago

A NullPointerException occurs when you invoke a method or access a field on a reference that’s null—including delayed initialization or accessing empty array elements (turn0search5 DZonesneppets+7Medium+7Cratecode+7). Common causes: • Accessing uninitialized objects or array elements • Auto-unboxing Integer when it’s null (int x = someInteger;) • Chained calls like person.address.city, where intermediate references may be null (turn0search5 Medium) Fixes: • Always check for null before use: java Copy code if (s != null) System.out.println(s.length()); (turn0search0 ZetCode+1Rollbar+1) • Use Optional.ofNullable() and ifPresent() or ifPresentOrElse(): java Copy code Optional.ofNullable(s).ifPresent(str -> System.out.println(str.length())); (turn0reddit12 DZone+10Reddit+10Medium+10) • Use Objects.requireNonNull() for parameter validation: java Copy code this.user = Objects.requireNonNull(user, "User cannot be null"); (turn0search4 ZetCode) • Apply static analysis with null annotations and tools like the Checker Framework to catch potential null dereferences before runtime (turn0search11 Codefiner+4DZone+4Reddit+4) • Consider the Null Object Pattern to return safe default objects instead of null.