IMHO, the best option is to return an Optional<RollingStock>, like the foillowing:

Copypublic Optional<RollingStock> getHeadPoint() {
    if (!train.isEmpty()) {
        // or even Optional.ofNullable, if you are not sure 
        // whether train.get(0) is null or not 
        return Optional.of(train.get(0));  
    } else {
        return Optional.empty();
    }
}

Assuming train is a collection, as an alternative to manual wrapping the value into an Optional you could use Stream API:

Copypublic Optional<RollingStock> getHeadPoint() {
    return train.stream()
                .findFirst();
}

In some cases using inline train.stream().findFirst() may be more preferable than wrapping it into a separate method.


Once you already modified your method getHeadPoint to return Optional<RollingStock> you can use it as follows:

Copy// ...
RollingStock headPoint = getHeadPoint().orElse(yourDefaultRollingStock);
// or
RollingStock headPoint = getHeadPoint().orElseGet(aMethodGettingYourDefaultRollingStock());
// or
RollingStock headPoint = getHeadPoint().orElseThrow(() -> new Exception("The train is empty!"));
// or
getHeadPoint().ifPresent(headPoint -> doSomethingWithHeadPoint(headPoint));
Answer from ETO 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 ...
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
I am looking for a recommendation here. I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined. Ta... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 17, 2011
java - Returning null in a method whose signature says return int? - Stack Overflow
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. ... Sign up to request clarification or add additional context in comments. ... @Jeppe: I'm guessing C# or Java. both of them have primitives, object wrappers ... More on stackoverflow.com
🌐 stackoverflow.com
Method return Optional or null?
If you think users of your library won't always remember to check for null, use an Optional. If null handling is very important, use an Optional. If null is a valid return that does not indicate unavailability or failure, use an Optional. I come from the world of functional programming, so I would say always use an optional. It enforces the check and makes sure people handle the errors. More on reddit.com
🌐 r/java
54
4
June 14, 2017
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
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 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
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.
🌐
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 - Return an optional value: Some programming languages provide the concept of an optional value, which can be used instead of returning null. An optional value is a type that can either contain a value or be empty.
Find elsewhere
🌐
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 ...
🌐
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
Avoid in-band error indicators. 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.
🌐
KapreSoft
kapresoft.com › java › 2023 › 12 › 10 › java-pitfalls-of-returning-null.html
Java • Pitfalls of Returning Null | KapreSoft
December 10, 2023 - This article discusses the use of Java Optional to introduce optional values instead of null. We will deep dive into understanding why developers prefer the Optional class to clearly communicate an optional value as opposed to a vague null representation of a variable. ... In Java, often times the ability to return a string representing the specified integer is a common task.
🌐
DeepSource
deepsource.com › directory › java › issues › JAVA-W1066
Method returning collection/array type returns `null` instead (JAVA-W1066) ・ Java
Consider returning empty collection instances or arrays instead of null. public List<Integer> method() { // ... method body if (/* some condition */) return Collections.emptyList(); } public int[] m2() { // ... method body if (/* some condition ...
🌐
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.

🌐
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.
🌐
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.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
February 20, 2026 - This presents the need for us to check the parameters or the response for a null value. Here, we can use Java Assertions instead of the traditional null check conditional statement:
🌐
Coderanch
coderanch.com › t › 99773 › engineering › Null-Empty-object-Return-Type
Null or Empty object (Return Type) (OO, Patterns, UML and Refactoring forum at Coderanch)
I recently changed from a null check to the boolean exists() check but then I had to recognize it could still return null so now I'm doing both [ September 10, 2005: Message edited by: Mr. C Lamont Gilbert ] ... Yes null is a String[]. Only a Roman would disagree "null is a String" doesn't have much meaning, simply because "is a" isn't well defined in this context. According to Liskov's Substitution Principle, null is not a subtype of String[]. Java's instanceof operator knows this, too - null is never an instance of any class.
🌐
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 - Stop Returning null — These 3 Alternatives Are Cleaner and Safer Null is not your friend. It’s a silent assassin It’s 2025. And yes, Java still lets you return null from methods. But should …
🌐
Scaledcode
blog.scaledcode.com › blog › effective-java › return_empty_not_null
Effective Java! Return Empty Collections or Arrays, Not Nulls
December 12, 2020 - private final List<Chesse> cheesesInStock = ... public List<Cheese> getInStockCheeses() { return cheesesInStock.isEmpty() ? null : new ArrayList<>(cheesesInStock); } ... List<Cheese> cheeses = getInStockCheeses(); if (cheeses != null && cheeses.contains(Cheese.CHEDDAR)) { System.out.println("We have cheese in stock"); } While the above code definitely works it requires more of the consumers than we should be requiring.