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.

🌐
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.
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

🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
February 20, 2026 - 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 ...
🌐
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 - While Java does not currently have the Elvis operator (?.), it’s worth looking out for in future versions. It’s popular in languages like Groovy for handling nulls gracefully. 🔴 Avoid Practice: Overusing null-safe operators, as can mask underlying design issues. 🟢 Good Practice: Use null-safe operators judiciously to improve code readability when dealing with potentially 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"; ...
🌐
Upwork
upwork.com › resources › articles › null in java: understanding the basics
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - Always perform null checks before accessing methods or properties of an object. ... ‍2. Optional class. Use the Optional class introduced in Java 8 to handle null type values more safely.
🌐
LabEx
labex.io › tutorials › java-how-to-handle-null-references-in-java-420548
How to handle null references in Java | LabEx
public class NullSafetyDemo { public Optional<String> processValue(String input) { return Optional.ofNullable(input) .filter(s -> !s.isEmpty()) .map(String::toUpperCase); } } public class UserService { public void processUser(User user) { Objects.requireNonNull(user, "User cannot be null"); // Safe processing } } ... By implementing these strategies in LabEx's Java development environment, developers can create more robust and error-resistant code. graph TD A[Advanced Null Strategies] --> B[Null Object Pattern] A --> C[Null Conditional Chaining] A --> D[Functional Null Handling]
Find elsewhere
🌐
DZone
dzone.com › coding › java › consistent null values handling in java
Consistent Null Values Handling in Java
December 16, 2019 - Without any additional efforts, strict following the convention above enables writing Java code which: Never throws NullPointerException and have all null values handled properly. Clearly and explicitly distinguishes nullable and non-nullable values in code and lets compiler enforce this distinction at compile time. ... Published at DZone with permission of Sergiy Yevtushenko. See the original article here. Opinions expressed by DZone contributors are their own. Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
🌐
Medium
medium.com › @mbanaee61 › mastering-null-in-java-55f20d4289da
Mastering 'null' in Java. Introduction | by Mahad | Medium
July 4, 2025 - public void sendEmail(@NonNull String recipient) { // IDE will warn if `null` is passed } ... Optional makes absence of value explicit and forces caller to handle it.
🌐
Belief Driven Design
belief-driven-design.com › better-null-handling-with-java-optionals-da974529bae
Better Null-Handling With Java Optionals | belief driven design
December 17, 2019 - 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 › 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.
🌐
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.
🌐
Ducmanhphan
ducmanhphan.github.io › 2020-02-01-Working-with-Nulls-in-Java
Working with Nulls in Java
February 1, 2020 - If an invalid parameter value is ... it can take appropriate action. ... Replace the null value with some default value such as using empty string, a negative value or an empty List....
🌐
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.
Top answer
1 of 3
1

If you're still getting an NPE, then the problem is in getNeighbours and not the second snippet.

  1. this.adjacencyList is null, -OR-
  2. this.adjacencyList.get(v) returns null.

Given that you're passing a name to a method that will then do a lookup by node, and that you can't call .get(someNodeRef) on a list, adjacencyList is probably some sort of hashmap, so your names are off and you should rename some things. Map's .get(x) method returns null if an entry is not found, so most likely the culprit is that v isn't in the map at all, and thus .get(v).isEmpty() throws NPE.

The fixes are as follows:

  1. You should NEVER return null when a valid sentinel value that carries the intended semantic meaning is available. A mouthful, but it means here: Why are you returning null when you intend to treat that the exact same way as 'zero nodes'? There is an instance of Iterable<Node> that properly represents the concept of zero nodes, and it isn't null. It's List.of() or equivalent: An empty list has no nodes. Great. That's what you intended. So return that.

  2. .get(v).isEmpty() is bad code here, as it would mean an NPE occurs if you ask for a non-existent node. Unless, of course, you want it to work that way. An easy way out is the defaulting mechanism: Call .getOrDefault instead:

if (!this.adjacencyList.getOrDefault(v, List.of()).isEmpty()) ....

except, of course, you should never be returning null when you can return an empty list instead, so your getNeighbours method becomes simply:

return adjacencyMap.getOrDefault(v, List.of());

that one-liner will fix all things.

In general, if you are writing code where null is dealt with in some way, and some sentinel value (such as a blank string or an empty list) is dealt with in the same way, your code is badly styled; however you got that null should have gotten you that empty value instead. e.g. if you ever write this:

if (x == null || x.isEmpty()) ...

you messed up. Figure out where you got x from. Update it there, make x the blank sentinel ("" for strings, List.of for lists, etcetera).

That, and use .getOrDefault and other such methods more: Methods that let you provide what should happen when e.g. a key is not found.

2 of 3
1

You should probably avoid returning null from your getNeighbors method. It's not good practice to return null for Iterables, Iterators and Collections, since an empty iterable would represent the same concept (there is nothing in that adjacency list) without all the dangers of null. And your code would be simpler. You can check if the iterable contains anything and if not then default to the full iterator.

🌐
LabEx
labex.io › tutorials › java-how-to-handle-null-values-when-joining-java-strings-417590
How to handle null values when joining Java strings | LabEx
The simplest approach to handle null values is to check for null before performing operations: Create a new Java file named BasicNullHandling.java in the /home/labex/project directory.
🌐
Royvanrijn
royvanrijn.com › blog › 2010 › 02 › handling-null-in-java
Handling null in Java
February 1, 2010 - If person or getName() produce a null the “?:” operator will return the default String. Sounds pretty good eh? The only problem is that this new operator didn’t make the final list of changes for Java 7. Fun fact: Do you know why the “?:”-operator is called the “Elvis”-operator? When viewed from the side, as smiley , it looks like Elvis. Including the big curl in his hair.
🌐
DEV Community
dev.to › hamzajvm › working-with-nulls-in-the-java-ecosystem-27ha
Working With Nulls in the Java Ecosystem - DEV Community
January 31, 2021 - Finally, having a good suite of tests will definitely help you detect programming bugs caused by nulls. There are third party annotations that will help you handle null values. However, in Java, there are no standard annotations to handle nulls.