# java.lang.NullPointerException

**Code:** `NullPointerException` · **Category:** Java · **Seen on:** Java, Android

Code called a method or accessed a field on a reference that is `null`.

## Meaning

Since Java 14, helpful NPE messages tell you exactly what was null: `Cannot invoke "String.length()" because "name" is null`. Read that message and the first stack frame in your own package.

## Common causes

- Uninitialized field or variable
- Method returned null (map lookup, repository find)
- Dependency injection didn’t populate a field (`@Autowired` on a `new`-created object)
- Auto-unboxing a null `Integer` to `int`
- Android: view not found (`findViewById` returns null) or used after destroy

## Quick fix

1. Read the “because X is null” part of the message
2. Find the first stack frame in your code
3. Return `Optional` or empty collections instead of null
4. Validate inputs with `Objects.requireNonNull(x, "x")`

## Detailed fix by platform

### Java

1. Optional instead of null checks:

```java
String city = Optional.ofNullable(user)
        .map(User::getAddress)
        .map(Address::getCity)
        .orElse("Unknown");
```


### Android

1. In Kotlin, prefer non-null types and `?.`/`?:`; in Java, annotate with `@Nullable/@NonNull` so lint warns you.

## Code examples

### Helpful NPE message (Java 14+)

```text
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "name" is null
    at com.example.App.greet(App.java:12)
```

## How to diagnose

1. **Message** — What is null (Java 14+ tells you)?
2. **Frame** — First frame in your package
3. **Origin** — Where should the value have been set?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/java/nullpointerexception)
