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.

Answer from Kayaman on Stack Overflow
🌐
Medium
medium.com › javarevisited › just-dont-return-null-dcdf5d77128f
Just Don’t Return null!. On my article Avoid Explicit null… | by JAVING | Javarevisited | Medium
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.
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
}
Discussions

Don’t return NULL
When the language doesn't have optionals 😂 Edit: as someone who has used js, I must say I'm offended that you don't realize the need to also have undefined and void More on reddit.com
🌐 r/SoftwareEngineering
141
112
March 13, 2024
java - Is there a way to avoid the "null" return? - Stack Overflow
I'm working on a method which draws a rectangle using asterisks. My method does return the desired rectangle, yet it obliges me to add a return statement with a "null" value. How can I ge... 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
Interesting. How to implement an option in Java? And in C++? ... I see both sides of this argument, and I realize some rather influential voices (e.g., Fowler) advocate not returning nulls in order to keep code clean, avoid extra error-handling blocks, etc. More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 17, 2011
java - How to avoid != null statements? - Software Engineering Stack Exchange
Explore Stack Internal ... Closed 8 years ago. I use code object != null to avoid NullPointerException. Is there a good alternative to solve this as follow ? ... This will not work for NullPointerException, when it is unknown that if the object is null or not. ... This is a different scenario. ... But the rationale is the same. ... I would say it's not your responsibility to check if the object is null, "someobject" should never be created and returned ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
April 9, 2018
🌐
DZone
dzone.com › data engineering › databases › 10 tips to handle null effectively
10 Tips to Handle Null Effectively
January 26, 2017 - We already know that null is not the best return value for a method and that we can make use of the Optional class to indicate that the value might be missing. But things are a bit different when we’re talking about collections. Since a collection can contain any amount of elements, it can also contain… 0 elements! There are even special emptyXxx methods in the Collections class that return such collections. Therefore, we should avoid returning null or complicating things with Optional and return an empty collection when there are no values to fill it with.
🌐
LinkedIn
linkedin.com › pulse › stop-returning-null-java-amir-boroumand
Stop Returning Null in Java
March 8, 2018 - This is annoying, difficult to read, and susceptible to run-time exceptions if anyone misses a null check anywhere. If the method returns a collection type, then we can simply substitute an empty collection. The Collections class has a static method for this purpose: ... Both of these return an immutable list so the calling code should make no attempt to modify it. Java 8 introduced a class called java.util.Optional that's designed to address the pain points associated with null values.
🌐
Medium
medium.com › @bubu.tripathy › clean-code-avoid-returning-null-9353498d6a01
Clean Code: Avoid Returning Null. To enhance code robustness and reduce… | by Bubu Tripathy | Medium
February 26, 2024 - ⭐️ Instead of returning null, consider using Optional<T> to explicitly indicate the potential absence of a value. This allows clients to handle both cases where a value is present and where it’s not. import java.util.Optional; // A service ...
🌐
O'Reilly
oreilly.com › library › view › java-by-comparison › 9781680505887 › f_0081.xhtml
Avoid Returning Null - Java By Comparison [Book]
Avoid Returning Null​ ​class​ SpaceNations {​ ​ ​static​ List<SpaceNation> nations = Arrays.asList(​ ​new​ SpaceNation(​"US"​, ​"United States"​),​ ... - Selection from Java By Comparison [Book]
🌐
Jonathangiles
java.jonathangiles.net › JLBP-15
Don't return null - Java Best Practices
In guaranteeing to return non-null values to callers of our API, our users can opt to not include the noisiness of the null check in their code base. It is important however, that should this approach be taken, that we ensure that it is applied consistently across an entire API. It is very easy to erode trust in an API if it fails to consistently apply patterns (and in failing to do so, causes the user to encounter unexpected null pointer exceptions). Java 8 introduced Optional as a way of lessening the possibility of null pointer exceptions, because when a method returns Optional, it guarantees that it will be non-null.
🌐
KapreSoft
kapresoft.com › java › 2023 › 12 › 10 › java-pitfalls-of-returning-null.html
Java • Pitfalls of Returning Null | KapreSoft
December 10, 2023 - Architectural choices can also play a role in minimizing the use of null. 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.
Find elsewhere
🌐
Reddit
reddit.com › r/softwareengineering › don’t return null
r/SoftwareEngineering on Reddit: Don’t return NULL
March 13, 2024 -

I’m planning on delivering a tech talk to my team on the pitfalls of explicitly returning nulls in production code, as opposed to using optionals where the language supports it or throwing exceptions when the value is expected to be present.

To make sure I’m not presenting an overly biased view, and to avoid getting blind-sided if someone raises a point I hadn’t considered, I want to hear examples of times you would actually prefer to explicitly return null.

Edit: Since some were curious and I neglected to specify, our team works predominantly in Java so we do have the Optional interface available to us. I have also worked with Go a bit and tbf I did like the ability to have multiple return values in the case of errors etc. I also don’t mind how Swift/Kotlin handle optionals and unwrapping them, I believe they handle it in a similar way.

🌐
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 ...
Top answer
1 of 3
7

toString implementations should return the string value that represents the object instead of printing it directly, as there's no guarantee that the caller of the method will want to print it. Imagine, for example, that you want to write the result of toString to a file -- how would you do it if it just printed to the console and returned nothing?

The best way to go about this is to modify your implementation of toString to build the asterisk rectangle as a string and return it without printing anything. But if you just want to solve this problem anyway, you can return an empty string instead of null.

2 of 3
4

So, draw doesn't actually return anything (useful), instead you're just printing the stars directly to the output stream.

Instead, what you should (probably be) doing, is building a String within the draw method which can be returned to the caller, for example...

public String draw() {
    StringJoiner outter = new StringJoiner("\n");
    for (int i = 1; i <= this.height; i++) {
        StringJoiner inner = new StringJoiner(" ");
        for (int j = 1; j <= this.width; j++) {
            inner.add("*");
        }
        outter.add(inner.toString());
    }
    return outter.toString();
}

Now, I'm using StringJoiner for simplicity (and because I'm lazy and it's just an amazing class), but you could equally get away with using StringBuilder, but you'd need to inject the additional properties yourself.

Then calling System.out.println(rectangle.toString()); would actually print the return result from the draw method

Runnable example...

import java.util.StringJoiner;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        Rectangle rectangle = new Rectangle(5, 3);

        System.out.println(rectangle.toString());
    }

    public class Rectangle {

        int width;
        int height;

        public Rectangle(int width, int height) {
            this.width = width;
            this.height = height;
        }

    public String draw() {
        StringJoiner outter = new StringJoiner("\n");
        for (int i = 1; i <= this.height; i++) {
            StringJoiner inner = new StringJoiner(" ");
            for (int j = 1; j <= this.width; j++) {
                inner.add("*");
            }
            outter.add(inner.toString());
        }
        return outter.toString();
    }

        public String toString() {
            return draw();
        }
    }
}
🌐
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.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
February 20, 2026 - Using Optional with collections allows us to design APIs that are sure to return non-null values, thus avoiding explicit null checks on the client.
🌐
Snyk
snyk.io › blog › how-to-prevent-nullpointerexceptions-in-java
How to prevent NullPointerExceptions in Java | Snyk
September 21, 2023 - This approach is important for preventing NullPointerExceptions because it ensures that the instance of the Singleton class is only created once and that subsequent calls to the getInstance() method return the same instance. This helps to prevent null values from being accidentally assigned to the instance variable and causing potential NullPointerExceptions. The Optional class is a powerful tool to avoid NullPointerExceptions by explicitly handling potential null values: import java.util.Optional; public class OptionalExample { private String someString; public OptionalExample(String someStri
🌐
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.
🌐
javathinking
javathinking.com › blog › how-do-i-avoid-checking-for-nulls-in-java
How to Avoid Null Checks in Java: Alternatives to `x != null` for Preventing NullPointerExceptions — javathinking.com
Avoid Optional as a field or method parameter—it’s designed for return values. Use annotations like @NonNull and @Nullable to enable static analysis (via IDEs or tools like FindBugs). These annotations flag potential null issues at compile time.
🌐
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.
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.

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.