If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.

Answer from user281377 on Stack Exchange
Top answer
1 of 11
47

If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.

2 of 11
22

Don't use null, use Optional

As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.

It's impossible to tell that could be null and what couldn't be.

Java 8 introduces a much better pattern: Optional.

And example from Oracle:

String version = "UNKNOWN";
if(computer != null) {
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null) {
    USB usb = soundcard.getUSB();
    if(usb != null) {
      version = usb.getVersion();
    }
  }
}

If each of these may or may not return a successful value, you can change the APIs to Optionals:

String name = computer.flatMap(Computer::getSoundcard)
    .flatMap(Soundcard::getUSB)
    .map(USB::getVersion)
    .orElse("UNKNOWN");

By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.

If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.

A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/


@Nonnull, @Nullable

Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.


Check when it makes sense

Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.

On the other hand, if null could be used and mean something, make sure to use it.


Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.

🌐
Upwork
upwork.com › resources › articles › {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - NullPointerException can significantly affect the stability of Java programs. When thrown, it stops the execution of the current thread, potentially leading to a program crash if not caught. This makes it essential for developers to handle null values proactively to ensure smooth and uninterrupted application execution. ... Uninitialized variables. Forgetting to initialize reference variables, leading to unexpected null values.
🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
List<String> list = new ArrayList<>(); list.add(null); list.forEach(System.out::println); // handle nulls carefully · Null and Default Values: Use null to signify optional parameters in methods. public void exampleMethod(String param1, String param2) { if (param2 == null) { param2 = "default"; } // logic here } Null in SQL Operations: Understand how null values are treated in SQL queries and avoid common pitfalls. ... Build your Java skills from the ground up and master programming concepts.
Top answer
1 of 4
3

For starters...the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:

if("constantString".equals(COMPLETEDDATE)) {
    // logic
}

But in general, your approach isn't correct.

The first one, as I commented, will always generate a NullPointerException is it's evaluated past country[23] == null. If it's null, it doesn't have a .length property. You probably meant to call country[23] != null instead.

The second approach only compares it against the literal string "null", which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail - in that case, you would rectify it as I described above.

Your third approach is correct in the sense that it's the only thing checking against null. Typically though, you would want to do some logic if the object you wanted wasn't null.

Your fourth approach is correct by accident; if COMPLETEDDATE is actually null, the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal "null".

2 of 4
1

To check null string you can use Optional in Java 8 as below: import Optional

import java.util.Optional;

import it as above

String str= null;
Optional<String> str2 = Optional.ofNullable(str);

then use isPresent() , it will return false if str2 contains NULL otherwise true

if(str2.isPresent())
{
//If No NULL 
}
else
{
//If NULL
}

reference: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

🌐
Ducmanhphan
ducmanhphan.github.io › 2020-02-01-Working-with-Nulls-in-Java
Working with Nulls in Java
These methods will not have to handle the null value. So, the solutions for never return null are: Return empty collection · Use Null Object pattern · Use Optional type · Spring Annotations · Belows are some annotations in org.springframework.lang package. ```java public class BookService { @NonNull private Integer defaultBookId; private void setDefaultBookId(@NonNull Integer id) { this.defaultBookId = id; } @NonNull private Integer getDefaultBookId() { return this.defaultBookId; } } This annotation allows our object can be null.
🌐
DEV Community
dev.to › siy › consistent-null-values-handling-in-java-3c5e
Consistent null values handling in Java - DEV Community
April 17, 2020 - If some external library/call can return null value, result should be immediately wrapped into Optional/Option/Maybe. Without any additional efforts strict following the convention above enables writing Java code which: never throws NullPointerException and have all null values handled properly.
🌐
Mezo Code
mezocode.com › home › handling null in java: 10 pro strategies for expert developers
Handling Null in Java: 10 Pro Strategies for Expert Developers | Mezo Code
October 16, 2024 - Tip: Use custom exceptions to provide more context about why a null value is unacceptable in a given scenario. Handle null effectively to prevent exceptions and make code easy to understand. Java provides tools to deal with null references. Be proactive and explicit about your assumptions to master null safety.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - But that is rarely applicable in real-world applications. Now let’s suppose that we’re working with an API that cannot accept null parameters or can return a null response that has to be handled by the client. This presents the need for us to check the parameters or the response for a null value. Here, we can use Java Assertions instead of the traditional null check conditional statement:
Find elsewhere
🌐
DZone
dzone.com › data engineering › databases › 10 tips to handle null effectively
10 Tips to Handle Null Effectively
January 26, 2017 - Passing null to indicate that there’s no value for a given argument might seem like a viable option. But it has two big disadvantages: You need to read the function’s implementation and figure out if it, and potentially every affected function down the way, can handle null value correctly.
🌐
Belief Driven Design
belief-driven-design.com › better-null-handling-with-java-optionals-da974529bae
Better Null-Handling With Java Optionals | belief driven design
Being a Smalltalk-inspired language, Objective-C doesn’t call methods or fields, it sends messages to objects. And sending a message to nil will not raise an exception, the message will be discarded silently. This can be great, you don’t have to null-check everything. But it’s also bad because you might not realize that a message wasn’t answered. With the release of Java 8, a straightforward way of handling null references was provided in the form of a new class: java.util.Optional<T>.
🌐
Medium
medium.com › @niteshthakur498 › working-effectively-with-null-values-in-modern-java-2025-edition-6101bfec26c3
Working Effectively with Null Values in Modern Java (2025 Edition) | by Nitesh Thakur | Medium
November 12, 2025 - The first and most crucial rule of modern null handling is simple: Do not return null from a method to indicate the absence of a value. When a method returns null, the contract is ambiguous, forcing the caller to guess whether a check is required.
🌐
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?" Java SE 8 introduces a new class called java.util.Optional<T> that is inspired from the ideas of Haskell and Scala.
🌐
Medium
medium.com › thefreshwrites › java-optional-and-either-handling-null-values-and-representing-two-possible-values-6a477a0fe189
Java Optional and Either: Handling Null Values and Representing Two Possible Values | by Samuel Catalano | Mar, 2023 | Medium | The Fresh Writes
March 10, 2023 - In this example, optionalName is an Optional that contains a value if name is not null, otherwise it is empty. The orElse() method returns the value if it is present, otherwise it returns the default value “Unknown”. Java Either is a class that provides a way to represent one of two possible values. While Optional handles null values, Either can handle two possible outcomes.
🌐
Logit
logit.io › blog › post › null-in-java
The Concept Of Null In Java
February 4, 2025 - Therefore, use direct references for fields and carefully analyse whether a field can be null or not at any given point. If your class is well-encapsulated, this should be fairly easy. Java bytecode, which is the instruction set for the Java Virtual Machine (JVM), has specific operations to handle 'null' values efficiently.
🌐
Foojay
foojay.io › home › optional in java: a swiss army knife for handling nulls and improving code quality
Optional in Java: A Swiss Army Knife for Handling Nulls and Improving Code Quality
February 20, 2023 - Nulls can cause all sorts of problems in your code, from NullPointerExceptions to convoluted if statements and error-prone logic. Fortunately, Java 8 introduced the Optional class, which offers a simple and powerful way to handle nulls and improve code quality.
🌐
DEV Community
dev.to › scottshipp › better-null-checking-in-java-ngk
Better Null-Checking in Java - DEV Community
January 11, 2019 - Unfortunately, I believe that there are plenty of times where the actual language forces null-checking on the programmer. And if the language doesn’t, someone else’s library does. ... Another option (ha ha, get it) is to use the Optional class introduced in Java 8. Baeldung’s Guide to Java 8 Optional covers the usage well. Great idea, honestly, if the code in question is handling a Stream.
🌐
Frankel
blog.frankel.ch › optional-nullable-type
Handling null: optional and nullable types
April 3, 2022 - Java has long been infamous for its NullPointerException. The reason for the NPE is calling a method or accessing an attribute of an object that has not been initialized. var value = foo.getBar().getBaz().toLowerCase(); Running this snippet may result in something like the following: Exception in thread 'main' java.lang.NullPointerException at ch.frankel.blog.NpeSample.main(NpeSample.
🌐
Quora
quora.com › What-are-the-best-practices-for-managing-null-value-effectively-in-Java
What are the best practices for managing null value effectively in Java? - Quora
Answer (1 of 3): The billion dollar mistake is quite interesting to deal with. One philosophy says that null is a valid value, which is fine for a more primitive object like a String or an Integer, but becomes rather messy if you ever have to call a method on said null object. In that scenario of...
🌐
OpenJDK
openjdk.org › jeps › 8303099
JEP draft: Null-Restricted and Nullable Types (Preview)
Enhance Java's reference types to let programmers express whether null references are expected as values of the type · Support conversions between types with different nullness properties, accompanied by warnings about possibly-mishandled null values · Compatibly interoperate with traditional Java code that makes no assertions about the null compatibility of its types, and support gradual adoption of these new features without introducing source or binary incompatibilities