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.
Top answer
1 of 16
102

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
101

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.

🌐
Coderanch
coderanch.com › t › 417559 › java › return-null
can we return null? (Java in General forum at Coderanch)
I am reviewing the code and found that method returns null in the below code. Is it valid to return null as it may lead others to take care of Nullpointer Exception?
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.
🌐
Medium
medium.com › @jadhavsid1101 › why-returning-null-from-functions-is-a-bad-idea-and-what-to-do-instead-d3074aa3c3b1
Why Returning Null from Functions is a Bad Idea and What to Do Instead | by Siddhesh Jadhav | Medium
May 25, 2023 - This way, the caller can still use the returned object without having to handle a null value. Use assertions: Assertions are statements that checkif a certain condition is true at runtime. By using assertions in the function, the developer can ensure that the function will not return null, and if it does, the assertion will fail and alert the developer to the problem. To illustrate these alternatives, let’s consider some examples with Java ...
🌐
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.
🌐
Sleepomeno
sleepomeno.github.io › blog › 2015 › 01 › 05 › else-return-null
else return null - while true live
I guess everybody has a story or ... in Java (or in any language with nullable values). Sooner or later you will make the acquaintance of the dreaded stacktrace line denoting that you did something terribly wrong, demanding a value where none exists, and you just wonder why, how the hell can that object be null?! during an hour of painful debugging… you know that? Good. Well, I won’t ponder over how to avoid it, ...
🌐
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.
🌐
Medium
elizarov.medium.com › null-is-your-friend-not-a-mistake-b63ff1751dd5
Null is your friend, not a mistake | by Roman Elizarov | Medium
March 2, 2019 - In corner cases, like the absence of something, it is a convention in Java to return some “null object” (empty collection, unfilled domain object, etc) or, as a lesser evil than returning null, to throw an exception.
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.

🌐
Coderanch
coderanch.com › t › 704073 › java › method-returns-null
why the method returns null? (Beginning Java forum at Coderanch)
By the way, youi don't appear to have a method returning null; you have nulls remaining in your array, which GG has correctly explained (). I was a bit surprised after reading this th‍read, to see what title you had given it. Beware of nulls in an array like that; they can cause you no end of trouble later. ... Daniel Demesmaecker wrote:And as for the location of the object, you're not trying to print the variable age, but the instances of Age.
🌐
JetBrains
jetbrains.com › help › inspectopedia › ReturnOfNull.html
Return of 'null' | Inspectopedia Documentation
Return of null in methods with return type java.util.Optional are always reported. Click Configure annotations to specify which annotations should be considered 'nullable'.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - 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: public void accept(Object param){ assert param != null; doSomething(param); }