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

🌐
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 FindPerson(), returning NULL seems like a better fit. Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).
🌐
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. What do you do when a suitable, well-behaved "empty" object is not available? In those cases, you should return an Optional<T>. Optional<T> was created especially for nullable return values.
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.
🌐
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
Find elsewhere
🌐
JetBrains
jetbrains.com › help › inspectopedia › ReturnOfNull.html
Return of 'null' | Inspectopedia Documentation
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 ...
🌐
Coderanch
coderanch.com › t › 376140 › java › method-return-null-anytime
should a method return null anytime? (Java in General forum at Coderanch)
But, for a method which returns a single value (find a Person by social security number), null is okay as an indicator that "I didn't find it." You're suggesting that an empty collection implies that there're no results instead of returning null? Frankly speaking I don't see the significant difference in either. Or what makes returning null so wrong/bad. As long as the documentation/Javadoc is clear about the meaning of the return value, it should suffice.
🌐
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 - 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 code: ... public List<String> getNames() { List<String> names = new ArrayList<>(); // code to populate the list return names.isEmpty() ? Collections.emptyList() : names; } In this example, if the names list is empty, we return an empty list using the Collections.emptyList() method.
🌐
DeepSource
deepsource.com › directory › java › issues › JAVA-W1066
Method returning collection/array type returns `null` instead (JAVA-W1066) ・ Java
method body if (/* some condition */) return null; } Consider returning empty collection instances or arrays instead of null.
🌐
KapreSoft
kapresoft.com › java › 2023 › 12 › 10 › java-pitfalls-of-returning-null.html
Java • Pitfalls of Returning Null | KapreSoft
December 10, 2023 - One of the most significant drawbacks of returning null is the heightened risk of NullPointerExceptions (NPEs). In Java, NPEs occur when a program attempts to use an object reference that has the null value. These exceptions are runtime errors, meaning they occur during the execution of the program and can cause it to crash if not properly handled. When methods return null, any operations performed on the returned value without null-checks can lead to these exceptions.
🌐
Medium
medium.com › @ujjawalr › stop-returning-null-these-3-alternatives-are-cleaner-and-safer-5b515ff628a8
Stop Returning null — These 3 Alternatives Are Cleaner and Safer | by Ujjawal Rohra | Medium
July 27, 2025 - Returning null from a method means you're handing a loaded gun to the caller. User user = userService.findById(id); if (user.getProfile().getImageUrl().startsWith("https")) { // NullPointerException waiting to happen } ... Forced the caller ...
Top answer
1 of 4
6

If you're using Java 8, consider the Optional class, but do note that it's not applicable everywhere.

Many think (me included) that Optional should be used only for return values, not parameters and especially not for object attributes. However as always there's no hard rule, just be careful that you don't replace null handling with Optional blindly, without understanding if you get any advantage from it.

In the example code for example, Optional won't do you any good. Since you perform some action regardless of null or not, you'll just be changing if(s == null) to if(s.isPresent()). However if the logic did something only if s is non-null, without an else you may be able to use Optional.ifPresent() to make things a bit cleaner. Of course there are other useful methods present in Optional that will give you cleaner code, such as the orElse() which can be used effectively for using default values.

2 of 4
5

Looks like you mean the special case pattern (particular implementations are the Option or the Null Object pattern).

There are Java implementations of the Option type, named Optional, in Java 8 and in the Guava libraries.

In your case, you'll be using Optional<SomeObject> and having this implementation (I'm using the Guava implementation):

Optional<SomeObject> getSomeObject(List<SomeObject>, int x) {
    /* Search for object in list that has a properties
        with value x */
    if (found) {
        return Optional.of(objectFound);
    } else {
        return Optional.absent(); // or Optional.empty(); in Java 8
    }
    // if objectFound variable is null when not found, you can simply use
    // return Optional.fromNullable(objectFound);
    // or return Optional.ofNullable(objectFound); in Java 8
}

So the code is self-explainable about returning an optional object. You would then have:

void doSomething(Optional<SomeObject> o) {
    if (o.isPresent()) {
        SomeObject someObject = o.get();
        /* Do action 1 */
    } else {
        /* Do action 2 */
    }
    // or opt.map(/* action 1 */).orElse(/* action 2 */); in Java 8
}
🌐
Coderanch
coderanch.com › t › 704073 › java › method-returns-null
why the method returns null? (Beginning Java forum at Coderanch)
Yes, naming conventions are important, not just things for us mods to get annoyed about You can introduce errors inot your code by poor naming of things. Also, GG: welcome to the Ranch ... 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 ().