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

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
You could also argue that the method ... passed in as empty or null. If you performed that check (threw back an exception), it will always return something other than null. ... Fowler POEAA - p. 496 Base Patterns - Special Case(null object) Bloch Effective Java, 2nd Edition ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 17, 2011
[java] Methods returning null should be annotated @Nullable
You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. ... There was an error while loading. Please reload this page. ... this is an idea for a new check ReturnMissingNullable: methods returning null ... More on github.com
🌐 github.com
2
November 24, 2017
Why use "return (null);" instead of "return null;" ?
And in C/C++/Java the parentheses are specifically required around loop-expressions only because there is no 'do' as in Algol, PL/1, Pascal, ... And it is certainly a pet peeve of mine that we went to all the trouble of inventing formula translators fifty years ago so we could use arithmetic precedence rather than reverse Polish, and there are *still* people afraid to use it. ... I found "return (null... More on thecodingforums.com
🌐 thecodingforums.com
21
June 6, 2006
Why we return null on java?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
37
25
August 20, 2024
🌐
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.
🌐
Coderanch
coderanch.com › t › 417559 › java › return-null
can we return null? (Java in General forum at Coderanch)
December 17, 2008 - 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?
🌐
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.

🌐
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.
Find elsewhere
🌐
Better Programming
betterprogramming.pub › checking-for-nulls-in-java-minimize-using-if-else-edae27016474
Checking for Nulls in Java? Minimize Using “If Else”
January 26, 2022 - If a value is present, returns the value, otherwise throws NoSuchElementException.¹ · In the case of null, if you want to throw an exception you could just use orElseThrow().
🌐
LinkedIn
linkedin.com › pulse › stop-returning-null-java-amir-boroumand
Stop Returning Null in Java
March 8, 2018 - Any methods that return a Blog type can now use Blog.NOT_FOUND instead of null. Exceptions should be reserved for exceptional conditions. If we always expect to find a value then throwing an exception makes sense. For example, we could throw an unchecked exception if an ID passed to our method isn't found in the database. throw new IllegalArgumentException("Invalid Blog ID"); The decision to use an exception when there is nothing to return is highly dependent on the nature of the application. The get() method in java.util.HashMap returns null in two situations:
🌐
GitHub
github.com › pmd › pmd › issues › 754
[java] Methods returning null should be annotated @Nullable · Issue #754 · pmd/pmd
November 24, 2017 - this is an idea for a new check ReturnMissingNullable: methods returning null should be annotated @Nullable. Invalid code: Date created; // failure: missing @Nullable public Date getCreated() { if (created == null) { return null; } else ...
Published   Nov 24, 2017
🌐
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 - If the caller of a function that returns null is not aware of the possibility of a null return value, they may try to access a property or method on the null object, which will result in a NullReferenceException.
🌐
Medium
medium.com › javarevisited › java-null-handling-with-optionals-b2ded1f48b39
Java - Null Handling With Optionals | by Ömer Kurular | Javarevisited | Medium
September 4, 2021 - For example, for the findByUsername method, we pass username and it returns related user from database. But, such user may not exist. In this case, we better return User wrapped inside Optional to handle nulls better. In this article, I talked about null handling in Java with Optionals.
🌐
GeeksforGeeks
geeksforgeeks.org › java › interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - In Java, null is also used to indicate that a method does not return any value. This is known as a "void" return type.
🌐
JetBrains
jetbrains.com › help › inspectopedia › ReturnOfNull.html
Return of 'null' | Inspectopedia Documentation
December 3, 2025 - 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 ...
🌐
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.
🌐
Upwork
upwork.com › resources › articles › {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - ‍ --CODE language-markup-- public class StaticMethodUtil { public static String processInput(String input) { if (input == null) { return "Default response"; } return "Processed: " + input; } } ... Null values have special meanings and behaviors in SQL operations. Understanding how nulls are handled in SQL is crucial to avoiding unexpected results. Null in SQL. Null represents the absence of a value in SQL. It's important to use IS NULL and IS NOT NULL to check for null values in SQL queries. --CODE language-markup-- SELECT * FROM users WHERE email IS NULL; ... Handling null in Java.
🌐
Chris Shennan
chrisshennan.com › blog › return-null-or-throw-exception-best-practice
Return null or Throw Exception - Best Practice? | Chris Shennan
December 5, 2022 - Returning `null` is the programmatic equivalent of "It's broken". Use exceptions to give context and allow you to tailor your error handling.
🌐
The Coding Forums
thecodingforums.com › archive › archive › java
Why use "return (null);" instead of "return null;" ? | Java | Coding Forums
June 6, 2006 - Except that one has more line noise. return(null) is a pet peeve of mine. Some people prefer to use the parentheses for consistency with function calls, loop tests, etc. I think they're also secretly insecure about operator precedence, and can't shake the feeling that a statement like "return 5 + x" will return five, discarding the value of x and losing forever the knowledge of what it contained.
🌐
W3Schools
w3schools.com › sql › sql_null_values.asp
SQL NULL Values - IS NULL and IS NOT NULL
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT NULL; Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Codemia
codemia.io › knowledge-hub › path › what_is_null_in_java
What is null in Java?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises