Hackforge Academy

Category: java

How to handle null in java

Published on 14 Feb 2026

Explanation

What is NullPointerException? In Java, null means the reference is not pointing to any object. If you try to use a null reference, Java throws: java.lang.NullPointerException

Code:


Explanation

Basic Null Check
Without Null Check String name = null; System.out.println(name.length());

Code:

With Null Check
String name = null;
if (name != null) {
  System.out.println(name.length());
} else {
    System.out.println("Name is null");
}

Explanation

Using Ternary Operator

Code:

String name = null;

int length = (name != null) ? name.length() : 0;

System.out.println(length);

Explanation

Using Objects Class (Java 7+) Java provides Objects utility class. Objects.requireNonNull() Throws custom error if null.

Code:

import java.util.Objects;

String name = null;
Objects.requireNonNull(name, "Name cannot be null");
Output:
Exception: Name cannot be null

Explanation

Objects.isNull() and Objects.nonNull()

Code:

import java.util.Objects;

String name = null;

if (Objects.isNull(name)) {
    System.out.println("Name is null");
}

Explanation

Using Optional (Java 8+) Optional helps avoid direct null handling.

Code:

import java.util.Optional;

String name = null;

Optional<String> optionalName = Optional.ofNullable(name);

optionalName.orElse("Default Name");
//Default Name

Explanation

With ifPresent()

Code:

Optional<String> optionalName = 
Optional.ofNullable("hackforge");

optionalName.ifPresent(n -> 
System.out.println(n));

Explanation

Using Java 14+ Objects.requireNonNullElse()

Code:

import java.util.Objects;


String name = null;


String result = Objects.requireNonNullElse(name, "Default");

System.out.println(result);

Explanation


Code:

1.Always validate method parameters

2.Use Optional for return types (not for fields)

3.Use constant-first string comparison

4.Avoid returning null β€” return empty list instead

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community