Attempting to use a reference that points to null.
A NullPointerException (NPE) is thrown when you try to use an object reference that hasn't been initialized and is currently `null`. Java requires objects to be instantiated before their methods or fields can be accessed, and calling anything on `null` is illegal.
Causes include: declaring a variable but not assigning it an object, a method returning `null` unexpectedly, an element in an array not being initialized, accessing a field of an object that was never created, or a collection method returning `null` instead of an empty collection.
1public class UserService {2 private String username;3 4 public static void main(String[] args) {5 UserService service = new UserService();6 // 'username' was never assigned, it's null7 System.out.println(service.username.toUpperCase());8 }9}1import java.util.Optional;2 3public class UserService {4 private String username;5 6 public UserService(String username) {7 this.username = username;8 }9 10 public static void main(String[] args) {11 // Fix 1: Ensure the object is properly initialized12 UserService service = new UserService("alice");13 System.out.println(service.username.toUpperCase()); // ALICE14 15 // Fix 2: Null check before use16 UserService service2 = new UserService(null);17 if (service2.username != null) {18 System.out.println(service2.username.toUpperCase());19 } else {20 System.out.println("Username is not set.");21 }22 23 // Fix 3: Use Optional for nullable values24 Optional<String> optionalName = Optional.ofNullable(service2.username);25 optionalName.ifPresentOrElse(26 name -> System.out.println(name.toUpperCase()),27 () -> System.out.println("No username provided.")28 );29 }30}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
The field `username` is declared but never assigned a value, so it defaults to `null`. Calling `.toUpperCase()` on `null` throws `NullPointerException: Cannot invoke "String.toUpperCase()" because "this.username" is null`. Java 17+ provides helpful NPE messages that name the exact null reference.