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
🌐
Coderanch
coderanch.com › t › 417559 › java › return-null
can we return null? (Java in General forum at Coderanch)
December 17, 2008 - Since, the pre-existing return statements return the appropriate values local to 'if' loops, 'return null' is added as per the java specifications - considering a situation if your control never enters the 'if' condition; since the return type of your method is Image (a subclass of the Almighty Object). [ December 17, 2008: Message edited by: Nitin Pathak ] ... But as I also said, you can choose to throw an exception instead: In the end, the choice is up to you.
Discussions

How can I return null in Java when the method is defined as int data type? - Stack Overflow
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 ... More on stackoverflow.com
🌐 stackoverflow.com
object oriented - Is it better to return NULL or empty values from functions/methods where the return value is not present? - Software Engineering Stack Exchange
Fowler POEAA - p. 496 Base Patterns - Special Case(null object) Bloch Effective Java, 2nd Edition Item 43: Return empty arrays or collections, not nulls ... Depends on your team consensus: in the case of mine, we agreed to return null for method that returns a single object indicating a value ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 17, 2011
arrays - Java - how to return a null in this String method? - Stack Overflow
3 The best way to test if a returned string is null in Java More on stackoverflow.com
🌐 stackoverflow.com
java - How to handle a null returned from a method? - Stack Overflow
Such exceptions are horrific to ... due to the place where the exception was thrown is most likely far away from the original implementation error. Your case is actually a good example of such behavior as it is not directly understandable where the NPE is coming from. In situations in which the appearance of a null value is inevitable (e.g. as @rzwitserloot pointed out, Java's Map get ... More on stackoverflow.com
🌐 stackoverflow.com
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.
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.
🌐
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.

🌐
JetBrains
jetbrains.com › help › inspectopedia › ReturnOfNull.html
Return of 'null' | Inspectopedia Documentation
March 31, 2026 - If a method is designed to return null, it is suggested to mark it with the @Nullable annotation - such methods will be ignored by this inspection. ... If the return type is java.util.Optional, an additional quick-fix to convert null to ...
Find elsewhere
🌐
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.
🌐
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.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Return Optional not null
The returned Optional object is itself never null! That would completely defeat the purpose of using {@code Optional<T>}. */ public Optional<LocalDate> getBirthDate() { return Optional.ofNullable(birthDate); } /** Debugging only. */ @Override public String toString(){ String SEP = ", "; return name + SEP + address + SEP + friends + SEP + birthDate; } // PRIVATE /** Required.
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.

🌐
javaspring
javaspring.net › blog › java-return-null
Java `return null`: An In-Depth Analysis — javaspring.net
To write more robust and maintainable code, developers should use techniques like the Optional class and document the cases where null is returned. By following these best practices, the risks associated with returning null can be minimized. Java Language Specification: https://docs.oracle.com/javase/specs/jls/se11/html/index.html
🌐
Sololearn
sololearn.com › en › Discuss › 1555596 › java-why-does-this-function-always-return-null
Java: Why does this function always return null? | Sololearn: Learn to code for FREE!
public class Funktionen { public static void main(String[] args) { String name1=null; randomName(name1); String name2=null; randomName(name2); System.out.println(name1); System.out.println(name2); } static String randomName(String a) { String [] nameList = { "Hans", "Paula", "Emma", "Florian" }; a = nameList[(byte)(Math.random()*nameList.length)]; return a; } } ... First, randomName method returns a String but you only invoke the method without assigning the return value to any variable, this is why your name1 and name2 variable are still null following the method invocation.
🌐
KapreSoft
kapresoft.com › java › 2023 › 12 › 10 › java-pitfalls-of-returning-null.html
Java • Pitfalls of Returning Null | KapreSoft
December 10, 2023 - When methods return null, any operations performed on the returned value without null-checks can lead to these exceptions. Given that NPEs are among the most common runtime errors in Java, their potential to disrupt application functionality cannot be overstated.
🌐
Sybase
infocenter.sybase.com › help › topic › com.sybase.infocenter.dc31652.1570 › html › java › CHDIJDAB.htm
Handling null argument values - Sybase Infocenter
Typically, you will write Java methods that specify Java parameter datatypes that are classes. In this case, nulls are handled without raising an exception. If you choose to write Java functions that use Java parameters that cannot handle null values, you can either: Include the returns null on null input clause when you create the SQLJ function, or
🌐
Upwork
upwork.com › resources › articles › null in java: understanding the basics
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - Learn the essentials of handling null in Java. This guide explains the concept, common pitfalls, and best practices for Java developers.
🌐
Baeldung
baeldung.com › home › java › java streams › can stream.collect() return the null value?
Can Stream.collect() Return the null Value? | Baeldung
January 8, 2024 - It turns out that the two null elements are successfully collected in the result list. Therefore, null elements in the stream won’t cause the collect() method to return null. When we use the standard collectors, the collect() method of the Java Stream API will not return null even if the stream is empty.
🌐
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 - Not only list documentation clearly states that it returns null when directory is missing, but modern IDEs flag this particular code with a warning right away. However, people do these kind of mistakes all the time when programming in Java. By now there is a big body of research showing how it happens. It turns out that most of the time our API functions are not supposed and are not expected by other developers to ...