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 - 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. Using Optional.empty() is a special case object that will safeguard the caller from a NullPointerException. Is my favourite approach instead of returning null, I personally use it a lot. Another common example of a similar special case object is Collections.emptyList() which will return an empty List that can be very useful in similar situations where we don’t want to return null but a List is required.
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.
🌐
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)
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.

🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Return Optional not null
When the return type of a method is Optional<T>, then the caller is forced into explicitly handling the null case. Example · In the example below, the class has a private LocalDate that holds a birth date. It has no "empty" default value. The getBirthDate method returns an Optional<LocalDate> to the caller. import java.time.LocalDate; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; public final class Human { /** Constructor.
🌐
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 - It turns out that most of the time our API functions are not supposed and are not expected by other developers to return null. 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.
Find elsewhere
🌐
KapreSoft
kapresoft.com › java › 2023 › 12 › 10 › java-pitfalls-of-returning-null.html
Java • Pitfalls of Returning Null | KapreSoft
December 10, 2023 - For instance, using a more functional style of programming with immutable objects and explicit error handling can reduce the reliance on null as a return value. Here’s a brief example illustrating how architectural choices can help avoid null through a more functional programming style: import java.util.Optional; // An example of an immutable object record Product(String name, double price) { } // A service class demonstrating explicit error handling class ProductService { // Simulated database or repository private static final Product[] products = { new Product("Laptop", 999.99), new Produ
🌐
JetBrains
jetbrains.com › help › inspectopedia › ReturnOfNull.html
Return of 'null' | Inspectopedia Documentation
Whether null values on array returns, collection object returns, plain object returns, or a combination of the three should be reported. Return of null in methods with return type java.util.Optional are always reported.
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.
🌐
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 - When a variable or object reference is set to null, it means it does not point to any valid object or value. This can cause runtime errors such as NullReferenceExceptions, and is a common source of bugs in software development. One common source of null references is returning null from functions.
🌐
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." James Carman, President<br />Carman Consulting, Inc. ... Sorry, didn't read Horatio's response first. But, man is he smart! He said the same thing I did (more or less)! James Carman, President<br />Carman Consulting, Inc. ... Originally posted by James Carman: You used a bad example, but the idea is sound.
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › java › MET55-J.+Return+an+empty+array+or+collection+instead+of+a+null+value+for+methods+that+return+an+array+or+collection
MET55-J. Return an empty array or collection instead of a null value for methods that return an array or collection - SEI CERT Oracle Coding Standard for Java - Confluence
For methods that return a set of values using an array or collection, returning an empty array or collection is an excellent alternative to returning a null value, as most callers are better equipped to handle and empty set than a null value. This noncompliant code example returns a null ArrayList when the size of the ArrayList is 0.
🌐
DeepSource
deepsource.com › directory › java › issues › JAVA-W1066
Method returning collection/array type returns `null` instead (JAVA-W1066) ・ Java
Returning null from such methods results in uglier code because now every caller has to check if the method has returned null. If the caller fails to do this, there's a chance that executing such code will result in a NullPointerException. When dealing with collections or arrays, the absence of values can usually be communicated by returning an empty instance instead of null.
🌐
Coderanch
coderanch.com › t › 704073 › java › method-returns-null
why the method returns null? (Beginning Java forum at Coderanch)
Remove the i++ at the end of your for-loop and the null values will disapear. rian bron wrote: doesn't it makes sense the printing the object in the array who has only 1 variable should print this variable value? It simply dosn't make sence to create an object with a single instance variable. In a real example the class would be for ex Person or Member or whatever and they wouldn't just have an age, but also for example a name, gender, address, etc...
🌐
GitHub
github.com › pmd › pmd › issues › 754
[java] Methods returning null should be annotated @Nullable · Issue #754 · pmd/pmd
November 24, 2017 - Date created; @Nullable public Date getCreated() { if (created == null) { return null; } else { return (Date) created.clone(); } }
Published   Nov 24, 2017