int is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer and then you can return null, and existing code that returns int will get autoboxed.

Nulls are assigned only to reference types, it means the reference doesn't point to anything. Primitives are not reference types, they are values, so they are never set to null.

Using the object wrapper java.lang.Integer as the return value means you are passing back an Object and the object reference can be null.

Answer from Nathan Hughes on Stack Overflow
๐ŸŒ
JanBask Training
janbasktraining.com โ€บ community โ€บ java โ€บ how-to-return-null-in-java
How to return null in java? | JanBask Training Community
October 6, 2022 - In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that. Also, this way, the caller would not have to check to see if a NULL was returned.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 417559 โ€บ java โ€บ return-null
can we return null? (Java in General forum at Coderanch)
Then programmers that call your method know that they should check if the return value is null: SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Hi there, Yes it can be considered a valid return technique, it just needs to be clearly documented in the Javadoc for that method e.g.
Top answer
1 of 16
103

StackOverflow has a good discussion about this exact topic in this Q&A. In the top rated question, kronoz notes:

Returning null is usually the best idea if you intend to indicate that no data is available.

An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.

Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.

Personally, I like to return empty strings for functions that return strings to minimize the amount of error handling that needs to be put in place. However, you'll need to make sure that the group that your working with will follow the same convention - otherwise the benefits of this decision won't be achieved.

However, as the poster in the SO answer noted, nulls should probably be returned if an object is expected so that there is no doubt about whether data is being returned.

In the end, there's no single best way of doing things. Building a team consensus will ultimately drive your team's best practices.

2 of 16
102

In all the code I write, I avoid returning null from a function. I read that in Clean Code.

The problem with using null is that the person using the interface doesn't know if null is a possible outcome, and whether they have to check for it, because there's no not null reference type.

In F# you can return an option type, which can be some(Person) or none, so it's obvious to the caller that they have to check.

The analogous C# (anti-)pattern is the Try... method:

public bool TryFindPerson(int personId, out Person result);

Now I know people have said they hate the Try... pattern because having an output parameter breaks the ideas of a pure function, but it's really no different than:

class FindResult<T>
{
   public FindResult(bool found, T result)
   {
       this.Found = found;
       this.Result = result;
   }

   public bool Found { get; private set; }
   // Only valid if Found is true
   public T Result { get; private set;
}

public FindResult<Person> FindPerson(int personId);

...and to be honest you can assume that every .NET programmer knows about the Try... pattern because it's used internally by the .NET framework. That means they don't have to read the documentation to understand what it does, which is more important to me than sticking to some purist's view of functions (understanding that result is an out parameter, not a ref parameter).

So I'd go with TryFindPerson because you seem to indicate it's perfectly normal to be unable to find it.

If, on the other hand, there's no logical reason that the caller would ever provide a personId that didn't exist, I would probably do this:

public Person GetPerson(int personId);

...and then I'd throw an exception if it was invalid. The Get... prefix implies that the caller knows it should succeed.

Top answer
1 of 12
77
It's an old solution to a problem that happened way before Java. I'm old, but I still use it because it's memory efficient and fast. Situational example.. You have a function that returns an int. If you know its always supposed to be positive, it's pretty common to return -1 to communicate that something went wrong, is absent, isn't finished doing something, etc. It's quick. Only requires a single 32/64 bit piece of memory. Solid choice to use when documented well. Instead of integer, let's say you have a class that hypothetically takes up 200 bytes of memory. I don't want to just stop my program because something isn't in a list, and I can't just return -1. I could create a default class that represents a problem just like "-1" does, but that's going to allocate 200 bytes. Assigning the variable to 'null' doesn't allocate 200 bytes. It just points to a universal 'null' memory address that is well understood by the JVM to mean "nothing." "Nothing" saves space and saves a lot of computation power from .equals(...) and even garbage collection. Is it worth having to rely on performing a null check constantly? Actually, yes. It is usually worth it. If people are used to dealing with null, it's not a problem. Coming from different languages where null is not allowed, you get a lot of NullPointerExceptions. Skill issue, though. Edit: Removed most mentions of exceptions to focus on why a new programmer might see "return null" and to appease the Spring devs who believe checked exceptions are relative to OPs question.
2 of 12
6
In some functions, if you can't find the value you want to return, you might return null instead. For example, imagine you have a method that is meant to search for an object in a collection that fits certain criteria. If your collection does not contain such an object, then your method might handle that by returning null. Generally though, this would not be considered great software design. It is very easy to run into runtime errors this way, for example, if a developer using such a method does not realize that it could return null.
๐ŸŒ
Medium
medium.com โ€บ javarevisited โ€บ just-dont-return-null-dcdf5d77128f
Just Donโ€™t Return null!
February 16, 2022 - Return a โ€œSpecial Caseโ€ object A special case object is something that we return instead of returning null. Thereโ€™s a pattern called null value object which I have already explained in the other article so I am not going to explain it here again but instead, I am going to use Java 8 Optional.empty() which is just Javaโ€™s implementation of that patter.
๐ŸŒ
Javapractices
javapractices.com โ€บ topic โ€บ TopicAction.do
Java Practices->Return Optional not null
an empty String you can usually simply return an empty object instead of null, and it will work fine, without special handling. In these cases, there's usually no need for the caller to explicitly handle the empty case.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 99773 โ€บ engineering โ€บ Null-Empty-object-Return-Type
Null or Empty object (Return Type) (OO, Patterns, UML and Refactoring forum at Coderanch)
I recently changed from a null check to the boolean exists() check but then I had to recognize it could still return null so now I'm doing both [ September 10, 2005: Message edited by: Mr. C Lamont Gilbert ] ... Yes null is a String[]. Only a Roman would disagree "null is a String" doesn't have much meaning, simply because "is a" isn't well defined in this context. According to Liskov's Substitution Principle, null is not a subtype of String[]. Java's instanceof operator knows this, too - null is never an instance of any class.
Find elsewhere
๐ŸŒ
Basis
documentation.basis.cloud โ€บ BASISHelp โ€บ WebHelp โ€บ commands โ€บ null_function_return_java_null_value.htm
NULL() Function - Return Java Null Value
The NULL() function returns a Java null value. It is typically used to check for a null value returned from a Java function.
๐ŸŒ
Refactoring.Guru
refactoring.guru โ€บ home โ€บ techniques โ€บ simplifying conditional expressions
Introduce Null Object
January 1, 2025 - Change the code so that it returns a null object. Find all places where the variables of the real class are compared with null. Replace these checks with a call for isNull(). If methods of the original class are run in these conditionals when a value doesnโ€™t equal null, redefine these methods in the null class and insert the code from the else part of the condition there.
๐ŸŒ
DZone
dzone.com โ€บ coding โ€บ languages โ€บ null object pattern in java
Null Object Pattern in Java
August 22, 2018 - I am using the shape interface for this example. Please note that I have created a method isNull() as well in the interface. It's nice to have a method, and I like it because I can better identify and control null-defined objects. This method will return false for all of the concrete classes.
๐ŸŒ
SourceMaking
sourcemaking.com โ€บ design_patterns โ€บ null_object โ€บ java โ€บ 1
Null Object Design Pattern in Java
Thus, the code which expects a list must verify that it in fact has one before continuing, which can complicate the design. By returning a null object (i.e. an empty list) instead, there is no need to verify that the return value is in fact a list. The calling function may simply iterate the list as normal, effectively doing nothing.
Top answer
1 of 3
5

The dilemma

If a variable with null value gets used in your program causing a NullPointerException, this is clearly a situation in your program which you did not expect. You must ask yourself the question: "Did I not expect it because I didn't take into consideration the possibility of a null value or did I assume the value could never be null here?"

If the answer is the latter, the problem isn't because you didn't handle the null value. The problem happened earlier, and you're only seeing the consequence of that error on the particular line it's used. In this case, simply adding a if (variable != null) isn't going to cut it. You'll wind up skipping lines you were supposed to execute because the variable was null, and you'll ultimately hit a line further on where you again assumed it wouldn't be null.

When null should be used

As a general rule, return null only when "absent" is a possible return value. In other words, your data layer may search for a record with a specific id. If that record isn't found, you can either throw an exception or simply return null. You may do either, but I prefer not to throw exceptions in situations where the strong possibility exists. So you return null instead of a value.

The caller of this method, presumably written by you, knows the possibility exists that the record may not exist and checks for null accordingly. There is nothing wrong with this in this case, though you should handle this possibility as soon as possible as otherwise everywhere in your program you will need to deal with the possibility of a null value.

Conclusion

In other words, treat null as a legitimate value, but deal with it immediately rather than wait. Ideally in your program, you should ever only have to check if it is null once in your program and only in the place where such a null value is handled.

For every value you expect to be non-null, you need not add a check. If it is null, accept that there is an error in your program when it was instantiated. In essence, favor fail fast over fail safe.

2 of 3
8

Deciding whether or not null is a allowed as an object value is a decision that you must make consciously for your project.

You don't have to accept a language construct just because it exists; in fact, it is often better to enforce a strict rule against any nullvalues in the entire project. If you do this, you don't need checks; if a NullPointerException ever happens, that automatically means that there is a defect in your code, and it doesn't matter whether this is signalled by a NPE or by some other sanity check mechanism.

If you can't do this, for instance because you have to interoperate with other libraries that allow null, then you do have to check for it. Even then it makes sense to keep the areas of code where null is possible small if possible. The larger the project, the more sense it makes to define an entire "anti-corruption layer" with the only purpose of preserving stricter value guarantees than is possible elsewhere.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - We can pass the null as an argument in java and we can print the same. The data type of argument should be Reference Type. But the return type of method could be any type as void, int, double or any other reference type depending upon the logic of program. Here, the method "print_null" will simply print the argument which is passed from the main method...
๐ŸŒ
KapreSoft
kapresoft.com โ€บ java โ€บ 2023 โ€บ 12 โ€บ 10 โ€บ java-pitfalls-of-returning-null.html
Java โ€ข Pitfalls of Returning Null | KapreSoft
December 10, 2023 - These tests effectively document how the processString() method handles null and non-null cases, providing a clear example of using unit tests to validate null behavior in Java. Implement null checks before using objects to avoid NPEs.
Top answer
1 of 1
1

In Java, null is only a valid value for reference types. It cannot represent a primitive type such as int. Here are some alternatives to consider:

  1. If you are using Java 8 or later, and are able to change the return type of the method you could use the OptionalInt type to represent an int value that may or may not be present. In that case, you would return OptionalInt.empty() in the case that there is no int value to return, and OptionalInt.of(x) to return an int x. Note that the caller will need to unwrap the int value (if it is present) using one of the other methods available on that class. This approach is often preferred for new code, as it makes the intention and usage very clear.
  2. If you are using an older Java version, another possibility is to change the return type to Integer. This is a wrapper class for int values that does allow for null to be returned. In addition, Java's auto-unboxing rules allow it to be used in contexts where an int value is expected, when the value is not null. However, if a null value is unboxed to an int value, it will result in a NullPointerException, so it is important to check for null before performing operations that would result in unboxing.
  3. If you need to use the int return type, it is common to use a sentinal value to represent an abnormal return. For example, if the normal return values for the method are all non-negative integers, you could use a value such as -1 to represent an absent return value. This is commonly used in older JDK methods such as String.indexOf().
  4. In some cases, it makes sense to throw an Exception when no valid value can be returned. It's only a good idea to use this approach for truly exceptional circumstances, as the runtime cost for throwing exceptions is much higher than normal method returns, and the flow of control can make the code harder to understand.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ [java] jackson json: how to return null object if any fields are missing?
r/learnprogramming on Reddit: [Java] Jackson Json: how to return null object if any fields are missing?
March 16, 2022 -

I have a model defined with Jackson like so:

package com.myapp.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.springframework.beans.factory.annotation.Required;

import java.util.List;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    @JsonProperty("id")
    public int id;

    @JsonProperty("name")
    public String name;
}

The behavior that I want is that if either the id or name is null, the Person object itself should be null.

Example test for the behavior:

@Test
void personIsNull() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode personNode = mapper.createObjectNode();
    Person person = mapper.treeToValue(personNode, Person.class);
    assertNull(person);    // this fails
}

The assertNull() fails since it is still initializing a Person object with null fields:

org.opentest4j.AssertionFailedError: 
Expected : null
Actual   : Person(id=null, name=null)

Is there an annotation that will return a null object if any of the fields are null?

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.