This is the most common problem to beginner to intermediate level programmer: they either don't know or don't trust the contracts they are participating in and defensively over check for nulls.

why the codes as follows is ugly?

 if( sth != null ) { ... }

It's not ugly as much as you know , but we thought it's extra check and not readable code if we have alot of null check condition in project. (For the case, if you accept where null is a valid response in terms of the contract; and ...)

But what is null safe or null safty exacty?
Below is my suggestion for "null safe" way to code according to my experienced and favorite authors.

For Collection Object Case

(1) Return empty arrays or collections, not nulls (Effective Java (See Item 43) - Joshua Bloch )

// The right way to return an array from a collection
private final List<Cheese> cheesesInStock = ...;

private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
/**
* @return an array containing all of the cheeses in the shop.
*/
public Cheese[] getCheeses() {
     return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
}

In similar fashion, a collection-valued method can be made to return the same immutable empty collection every time it needs to return an empty collection. The Collections.emptySet, emptyList, and emptyMapmethods provide exactly what you need, as shown below:

// The right way to return a copy of a collection
public List<Cheese> getCheeseList() {
    if (cheesesInStock.isEmpty())
     return Collections.emptyList(); // Always returns same list
   else
     return new ArrayList<Cheese>(cheesesInStock);
}

In summary, there is no reason ever to return null from an array- or collection-valued method instead of returning an empty array or collection.

(2) Don't Return Null - (Clean Code - Uncle Bob)
In many cases, special case objects are an easy remedy. Imagine that you have code like this:

List<Employee> employees = getEmployees();
if (employees != null) {
  for(Employee e : employees) {
   totalPay += e.getPay();
  }
}

Right now, getEmployees can return null, but does it have to? If we change getEmployeeso that it returns an empty list, we can clean up the code:

List<Employee> employees = getEmployees();
for(Employee e : employees) {
  totalPay += e.getPay();
}

Fortunately, Java has Collections.emptyList(), and it returns a predefined immutable list that we can use for this purpose:

public List<Employee> getEmployees() {
   if( .. there are no employees .. ) 
     return Collections.emptyList();
}

If you code this way, you will minimize the chance of NullPointerExceptions and your code will be cleaner.

Don’t Pass Null
Returning null from methods is bad, but passing null into methods is worse. Unless you are working with an API which expects you to pass null, you should avoid passing null in your code whenever possible.

Let’s look at an example to see why. Here is a simple method which calculates a metric for two points:

public class MetricsCalculator 
{
    public double xProjection(Point p1, Point p2) {
        return (p2.x – p1.x) * 1.5;
    }
…
}

What happens when someone passes null as an argument?

calculator.xProjection(null, new Point(12, 13));

We’ll get a NullPointerException, of course.

How can we fix it? We could create a new exception type and throw it:

public class MetricsCalculator 
{
    public double xProjection(Point p1, Point p2) {
        if (p1 == null || p2 == null) {
        throw InvalidArgumentException(
        "Invalid argument for MetricsCalculator.xProjection");
        }
        return (p2.x – p1.x) * 1.5;
    }
}


Is this better? It might be a little better than a nullpointerexception, but remember, we have to define a handler for InvalidArgumentException. What should the handler do? Is there any good course of action?

There is another alternative. We could use a set of assertions:

public class MetricsCalculator 
    {
        public double xProjection(Point p1, Point p2) {
        assert p1 != null : "p1 should not be null";
        assert p2 != null : "p2 should not be null";
        return (p2.x – p1.x) * 1.5;
    }
}

It’s good documentation, but it doesn’t solve the problem. If someone passes null, we’ll still have a runtime error.
In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default. When you do, you can code with the knowledge that a null in an argument list is an indication of a problem, and end up with far fewer careless mistakes.

Extra Note: The null-return idiom is likely a holdover from the C programming language, in which array lengths are returned separately from actual arrays. In C, there is no advantage to allocating an array if zero is returned as the length.

For Non-Collection Object Case

(1) Use Null Object Pattern (old approach)
eg.(assume you are using dao pattern to access db)
All you need to do is return an empty object - say a customer entry you would have in your DAO something like.....

if (result == null) { return new EmptyUser(); }

where EmptyUser extends User and returns appropriate entries to getter calls to allow the rest of your code to know it is an empty object (id = -1 etc) code sample:

public class User {
    private int id;
    private String name;
    private String gender;
    public String getName() {
       //Code here
    }
    public void setName() {
       //Code here
    }
}

public class EmptyUser extends User {

    public int getId() {
       return -1;
    }

    public String getName() {
       return String.Empty();
   }
}

public User getEntry() {
   User result = db.query("select from users where id = 1");
   if(result == null) {
       return new EmptyUser();
   }
   else {
       return result;
    }
}

(2) Use Java 8 Optional
Indeed introducing null reference is probably one of the worse mistake in the programming languages' history even its creator Tony Hoare calls it his billion-dollar mistake.

Here are the best alternatives to null according to new Java version:

2.1. Java 8 and above

Starting from Java 8 you can use java.util.Optional.

Here is an example of how you could use it in not null return case:

public Optional<MyEntity> findMyEntity() {
    MyEntity entity = // some query here
    return Optional.ofNullable(entity);
}


2.2. Prior to Java 8

Before Java 8 you can use com.google.common.base.Optional from Google Guava.

Here is an example of how you could use it in not null return case:

public Optional<MyEntity> findMyEntity() {
    MyEntity entity = // some query here
    return Optional.fromNullable(entity);
}



Note for Null Object Pattern Vs Java 8 Optional:

I definitively prefer Optional it is much more generic and it has been adopted by Oracle and Google, 2 of the biggest IT companies in the world which give a lot of credits to it.

I would even say that Null Object Pattern doesn't make any sense anymore in Java, it is outdated, Optional is the future if you check a little bit what's new in Java 9, you will see that Oracle makes Optional go a little bit further, read this article

Answer from Ye Win on Stack Overflow
Top answer
1 of 4
6

This is the most common problem to beginner to intermediate level programmer: they either don't know or don't trust the contracts they are participating in and defensively over check for nulls.

why the codes as follows is ugly?

 if( sth != null ) { ... }

It's not ugly as much as you know , but we thought it's extra check and not readable code if we have alot of null check condition in project. (For the case, if you accept where null is a valid response in terms of the contract; and ...)

But what is null safe or null safty exacty?
Below is my suggestion for "null safe" way to code according to my experienced and favorite authors.

For Collection Object Case

(1) Return empty arrays or collections, not nulls (Effective Java (See Item 43) - Joshua Bloch )

// The right way to return an array from a collection
private final List<Cheese> cheesesInStock = ...;

private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
/**
* @return an array containing all of the cheeses in the shop.
*/
public Cheese[] getCheeses() {
     return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
}

In similar fashion, a collection-valued method can be made to return the same immutable empty collection every time it needs to return an empty collection. The Collections.emptySet, emptyList, and emptyMapmethods provide exactly what you need, as shown below:

// The right way to return a copy of a collection
public List<Cheese> getCheeseList() {
    if (cheesesInStock.isEmpty())
     return Collections.emptyList(); // Always returns same list
   else
     return new ArrayList<Cheese>(cheesesInStock);
}

In summary, there is no reason ever to return null from an array- or collection-valued method instead of returning an empty array or collection.

(2) Don't Return Null - (Clean Code - Uncle Bob)
In many cases, special case objects are an easy remedy. Imagine that you have code like this:

List<Employee> employees = getEmployees();
if (employees != null) {
  for(Employee e : employees) {
   totalPay += e.getPay();
  }
}

Right now, getEmployees can return null, but does it have to? If we change getEmployeeso that it returns an empty list, we can clean up the code:

List<Employee> employees = getEmployees();
for(Employee e : employees) {
  totalPay += e.getPay();
}

Fortunately, Java has Collections.emptyList(), and it returns a predefined immutable list that we can use for this purpose:

public List<Employee> getEmployees() {
   if( .. there are no employees .. ) 
     return Collections.emptyList();
}

If you code this way, you will minimize the chance of NullPointerExceptions and your code will be cleaner.

Don’t Pass Null
Returning null from methods is bad, but passing null into methods is worse. Unless you are working with an API which expects you to pass null, you should avoid passing null in your code whenever possible.

Let’s look at an example to see why. Here is a simple method which calculates a metric for two points:

public class MetricsCalculator 
{
    public double xProjection(Point p1, Point p2) {
        return (p2.x – p1.x) * 1.5;
    }
…
}

What happens when someone passes null as an argument?

calculator.xProjection(null, new Point(12, 13));

We’ll get a NullPointerException, of course.

How can we fix it? We could create a new exception type and throw it:

public class MetricsCalculator 
{
    public double xProjection(Point p1, Point p2) {
        if (p1 == null || p2 == null) {
        throw InvalidArgumentException(
        "Invalid argument for MetricsCalculator.xProjection");
        }
        return (p2.x – p1.x) * 1.5;
    }
}


Is this better? It might be a little better than a nullpointerexception, but remember, we have to define a handler for InvalidArgumentException. What should the handler do? Is there any good course of action?

There is another alternative. We could use a set of assertions:

public class MetricsCalculator 
    {
        public double xProjection(Point p1, Point p2) {
        assert p1 != null : "p1 should not be null";
        assert p2 != null : "p2 should not be null";
        return (p2.x – p1.x) * 1.5;
    }
}

It’s good documentation, but it doesn’t solve the problem. If someone passes null, we’ll still have a runtime error.
In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default. When you do, you can code with the knowledge that a null in an argument list is an indication of a problem, and end up with far fewer careless mistakes.

Extra Note: The null-return idiom is likely a holdover from the C programming language, in which array lengths are returned separately from actual arrays. In C, there is no advantage to allocating an array if zero is returned as the length.

For Non-Collection Object Case

(1) Use Null Object Pattern (old approach)
eg.(assume you are using dao pattern to access db)
All you need to do is return an empty object - say a customer entry you would have in your DAO something like.....

if (result == null) { return new EmptyUser(); }

where EmptyUser extends User and returns appropriate entries to getter calls to allow the rest of your code to know it is an empty object (id = -1 etc) code sample:

public class User {
    private int id;
    private String name;
    private String gender;
    public String getName() {
       //Code here
    }
    public void setName() {
       //Code here
    }
}

public class EmptyUser extends User {

    public int getId() {
       return -1;
    }

    public String getName() {
       return String.Empty();
   }
}

public User getEntry() {
   User result = db.query("select from users where id = 1");
   if(result == null) {
       return new EmptyUser();
   }
   else {
       return result;
    }
}

(2) Use Java 8 Optional
Indeed introducing null reference is probably one of the worse mistake in the programming languages' history even its creator Tony Hoare calls it his billion-dollar mistake.

Here are the best alternatives to null according to new Java version:

2.1. Java 8 and above

Starting from Java 8 you can use java.util.Optional.

Here is an example of how you could use it in not null return case:

public Optional<MyEntity> findMyEntity() {
    MyEntity entity = // some query here
    return Optional.ofNullable(entity);
}


2.2. Prior to Java 8

Before Java 8 you can use com.google.common.base.Optional from Google Guava.

Here is an example of how you could use it in not null return case:

public Optional<MyEntity> findMyEntity() {
    MyEntity entity = // some query here
    return Optional.fromNullable(entity);
}



Note for Null Object Pattern Vs Java 8 Optional:

I definitively prefer Optional it is much more generic and it has been adopted by Oracle and Google, 2 of the biggest IT companies in the world which give a lot of credits to it.

I would even say that Null Object Pattern doesn't make any sense anymore in Java, it is outdated, Optional is the future if you check a little bit what's new in Java 9, you will see that Oracle makes Optional go a little bit further, read this article

2 of 4
1

Null pointers are arguably the most common source of runtime crashes - they are effectively ticking time-bombs. The dreaded null-check in java is considered a code smell by most senior developers, and is usually a sign of bad design.

A far safer approach is to use a Null Object Pattern as zhc mentioned. In this case you create an uninitialized object whenever you declare it rather than let it sit as a null until populated.

An overly simplified example of this would be to always instantiate a String with "". An empty label (in my opinion) is preferable to a crash.

🌐
DEV Community
dev.to › nfrankel › null-safety-kotlin-vs-java-13pn
Null safety: Kotlin vs. Java - DEV Community
February 16, 2023 - Developers praise Kotlin for its null-safety: it's the result of its null-handling mechanism baked into the language design. Java will never be able to compete with Kotlin in this regard, as Java language architects value backward compatibility over code safety.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
January 8, 2024 - Here, @NonNull makes it clear that the argument cannot be null. If the client code calls this method without checking the argument for null, FindBugs would generate a warning at compile time. Developers generally rely on IDEs for writing Java code.
🌐
Spring
spring.io › blog › 2025 › 03 › 10 › null-safety-in-spring-apps-with-jspecify-and-null-away
Null Safety in Spring applications with JSpecify and NullAway
JSpecify is a set of annotations, specifications and documentation designed to ensure the null safety of Java applications and libraries in the IDE or during the compilation thanks to tools like NullAway.
🌐
Kotlin
kotlinlang.org › docs › null-safety.html
Null safety | Kotlin Documentation
In Java, this would be the equivalent of a NullPointerException, or an NPE for short. Kotlin explicitly supports nullability as part of its type system, meaning you can explicitly declare which variables or properties are allowed to be null. Also, when you declare non-null variables, the compiler enforces that these variables cannot hold a null value, preventing an NPE. Kotlin's null safety ensures safer code by catching potential null-related issues at compile time rather than runtime.
🌐
FB
engineering.fb.com › home › retrofitting null-safety onto java at meta
Retrofitting null-safety onto Java at Meta
November 18, 2022 - We developed a new static analysis tool called Nullsafe that is used at Meta to detect NullPointerException (NPE) errors in Java code. Interoperability with legacy code and gradual deployment model were key to Nullsafe’s wide adoption and allowed us to recover some null-safety properties in the context of an otherwise null-unsafe language in a multimillion-line codebase.
🌐
DEV Community
dev.to › rytheturtle › null-safety-in-java-3mde
Null Safety In Java - DEV Community
February 11, 2024 - Introduced in Java 1.8, the Optional class gives a null safe standard library class for Java developers to express that a value may or may not be present. Null safety is an important characteristic of code, so much so that null safety is a first class feature of many newer programming languages.
Find elsewhere
🌐
Spring
docs.spring.io › spring-framework › reference › core › null-safety.html
Null-safety :: Spring Framework
Although Java does not let you express nullness markers with its type system yet, the Spring Framework codebase is annotated with JSpecify annotations to declare the nullability of its APIs, fields, and related type usages. Reading the JSpecify user guide is highly recommended in order to get familiar with those annotations and semantics. The primary goal of this null-safety arrangement is to prevent a NullPointerException from being thrown at runtime via build time checks and to use explicit nullability as a way to express the possible absence of value.
🌐
GitHub
github.com › mariha › null-safety
GitHub - mariha/null-safety: A holistic approach to bring null-safety to the code written in Java.
This is where @javax.validation.constraints.NotNull annotation and alike come to play. We wrote a test which ensures that each field of a class implementing NullsafetyBoundary is either @NotNull (correctness guarded by bindings framework or our own deserializer (example), and the null-safety default) or @Nullable for compile-time verification of correct usage further-on based on data-flow analyses.
Author   mariha
🌐
Oracle
oracle.com › java › technical details
Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!
Scala has a similar construct called Option[T] to encapsulate the presence or absence of a value of type T. You then have to explicitly check whether a value is present or not using operations available on the Option type, which enforces the idea of "null checking." You can no longer "forget to do it" because it is enforced by the type system. OK, we diverged a bit and all this sounds fairly abstract. You might now wonder, "so, what about Java SE 8?"
🌐
Frankel
blog.frankel.ch › null-safety-java-vs-kotlin
Null safety: Kotlin vs. Java
February 12, 2023 - Java was incepted when null-safety was not a big concern. Hence, NullPointerException occurrences are common. The only safe solution is to wrap every method call in a null check.
🌐
Reflectoring
reflectoring.io › spring-boot-null-safety-annotations
Protect Your Code from NullPointerExceptions with Spring's Null-Safety Annotations
January 31, 2022 - Null-safety ensures that we have added proper checks in the code to guarantee the object reference cannot be null or possible safety measures are taken when an object is null, after all.
🌐
Reddit
reddit.com › r/java › plans for compile-time null pointer safety?
r/java on Reddit: Plans for Compile-time Null Pointer Safety?
July 16, 2022 -

Are there any plans in the works for Java to get null pointer safety at compile time (maybe similar to Kotlin's implementation) in the future? At the moment, I sprinkle "Objects.requireNonNull" in my methods (which admittedly has saved me countless hours of debugging null issues)...but I find this to be inefficient compared to a compile-time solution. I'm also not satisfied with the other run-time solutions of dealing with null such as with the "Optional" type or annotations.

I think Java has been doing great things to close the gap between itself and languages like Kotlin (e.g. records instead of data classes as well as virtual threads instead of coroutines), but I find the lack of compile-time null pointer safety in Java, as well as my lack of being able to find any future plans for it, to be a potential dealbreaker for new projects in which I get to decide the language.

🌐
Quora
quora.com › Why-is-Java-still-missing-null-safety
Why is Java still missing null safety? - Quora
Answer (1 of 4): Good question. Java is safer than C++ in this respect; NullPointerException at least does not crash the process in the OS. Java 8 Optional has given us a bit more for streams and method returns, but is still not quite there for representing values that might not be there. You ...
🌐
Hacker News
news.ycombinator.com › item
Retrofitting null-safety onto Java at Meta | Hacker News
September 17, 2022 - This is perfectly legal code, where the optional wrapper itself is null: · Optional<String> getMiddleName() { return null; }
🌐
Medium
tamerardal.medium.com › null-safety-avoid-null-pointer-exception-in-java-3cd623693418
Null Safety: Avoid Null Pointer Exception in Java | by Tamer Ardal | Medium
October 17, 2024 - Whether you use traditional checks, Optional, or the Objects class, you can write code that is both readable and safe from null pointer exceptions. By leveraging these standard Java features, you can keep your codebase lightweight and maintainable without relying on third-party dependencies.
🌐
Reddit
reddit.com › r/java › is null-safety coming to java? (the big kotlin advantage)
r/java on Reddit: Is null-safety coming to Java? (the big Kotlin advantage)
February 14, 2016 -

I learned today about the null type system in Kotlin. It is very nice to have compiler checking for nulls.

I wish I could use this in Java, but unlike Kotlin, it would be not default.

I want to specify non nulls with variable?.

A variable? is a reference that have been compiler checked for not being null.

Top answer
1 of 5
5

I don't think that Java designers are thinking in terms of compile time null checks as of now because it isn't a part of Java 9 specs(Java 9 is the next Java version due in July 2017). Also, since Optional has been introduced in Java 8 the designers have already taken a different approach to handling null pointer exceptions. An optional value prevents the notorious null pointer checks with its capability to hold both null and non-null values for the same variable.

2 of 5
1

I've often thought that Null should be a first class single-instance Object that had specific characteristics of being able to accept any method request and always returning itself as the result. Smalltalk had something similar in that you could register a default message handler that would take any incoming message the main object didn't recognize so you didn't have to deal with unknown message errors.

If Java had an object like this then NullPointerExceptions would not need to be raised in situations like:

foo.bar().baz().grok().toString()

If 'foo' or any of the chained methods returned the "Null" object every call would result in the same object being returned and the final 'toString()' would provide a proper value.

The Null object would always be part of the return set for any method that returns an Object so you would still want to handle if that was the return, but checking return values is something that should always happen anyway. All this would do is eliminate the NullPointerException if a method was called on Null.

🌐
Medium
medium.com › @ksaquib › mastering-java-8s-optional-t-a-guide-to-null-safety-74dfe63bb292
Mastering Java 8’s Optional<T>: A Guide to Null Safety | by Saquib Khan | Medium
April 30, 2024 - Java 8 introduced a powerful new class called Optional<T> aimed at combating these exceptions by encouraging developers to handle the absence of values more gracefully. Optional<T> is a container object used to represent a value that is either present or absent. It provides a clear and explicit way to deal with the absence of a value, rather than relying on null, thus helping avoid NullPointerExceptions.
🌐
Spring
spring.io › blog › 2025 › 11 › 12 › null-safe-applications-with-spring-boot-4
Null-safe applications with Spring Boot 4
The easiest way to benefit from Spring null-safety is to upgrade to Spring Boot 4 and use an IDE that supports JSpecify annotations to provide feedback to the developer on how to handle potential nullability issues detected from Spring APIs usage.