Exception in thread 'main' java.lang.NullPointerException
Exception in thread 'main' java.lang.NullPointerException
DodaTech
3 min read
NullPointerException fires when you call a method on null. It is the most common Java runtime exception and indicates a missing object initialization.
What It Means
You have a reference variable that points to nothing (null), but your code tries to use it as if it points to a real object. The JVM throws a NullPointerException at the exact line where the null dereference occurs.
Why It Happens
- You declared a variable but forgot to initialize it before use.
- A method returns
nullwhen you expected a valid object. - An array element or collection entry is
null. - You chain method calls without checking intermediate results.
- A constructor or factory method failed silently and returned
null.
How to Fix It
1. Find the exact null reference
Look at the stack trace — it tells you the exact line number. Break that line into smaller steps to identify which variable is null:
// Before — one-liner, can't tell which is null
int length = getService().getConfig().getName().length();
// After — each step is checkable
Service svc = getService();
if (svc == null) throw new IllegalStateException("service is null");
Config cfg = svc.getConfig();
if (cfg == null) throw new IllegalStateException("config is null");
String name = cfg.getName();
int length = name != null ? name.length() : 0;2. Add null checks at boundaries
Validate method parameters and return values:
public void processOrder(Order order) {
Objects.requireNonNull(order, "order must not be null");
// safe to use order below
}3. Use Optional for nullable returns
// Instead of returning null
public Optional<Customer> findCustomer(String id) {
if (id == null || id.isBlank()) {
return Optional.empty();
}
// ... lookup logic
return Optional.ofNullable(databaseResult);
}
// Caller handles both cases
Customer c = findCustomer("123")
.orElseThrow(() -> new RuntimeException("Customer not found"));4. Use the ternary operator for defaults
String label = getLabel() != null ? getLabel() : "Default label";5. Enable NPE help messages (Java 14+)
// Pass -XX:+ShowCodeDetailsInExceptionMessages to the JVM
// This prints which variable was null in the error messageBuilt by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro