Method 4 is best.

if(foo != null && foo.bar()) {
   someStuff();
}

will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.

Answer from Jared Nielsen on Stack Overflow
🌐
Oracle
oracle.com › java › technical details
Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!
Scala has a similar construct called Option[T] to encapsulate the presence or absence of a value of type T. You then have to explicitly check whether a value is present or not using operations available on the Option type, which enforces the idea of "null checking." You can no longer "forget to do it" because it is enforced by the type system. OK, we diverged a bit and all this sounds fairly abstract. You might now wonder, "so, what about Java SE 8?" Java SE 8 introduces a new class called java.util.Optional<T> that is inspired from the ideas of Haskell and Scala.
🌐
Winterbe
winterbe.com › posts › 2015 › 03 › 15 › avoid-null-checks-in-java
Avoiding Null Checks in Java 8 - winterbe
This post describes techniques how to prevent null checks and NullPointerExceptions in Java 8 in order to improve null safety and code readability.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
January 8, 2024 - Generally, null variables, references and collections are tricky to handle in Java code. They are not only hard to identify but also complex to deal with. As a matter of fact, any miss in dealing with null cannot be identified at compile time and results in a NullPointerException at runtime. In this tutorial, we’ll take a look at the need to check for null in Java and various alternatives that help us to avoid null checks in our code.
🌐
DZone
dzone.com › coding › java › java 8 optional: handling nulls properly
Java 8 Optional: Handling Nulls Properly
June 18, 2018 - Java 8 introduced the Optionalclass to make handling of nulls less error-prone. For example, the following program to pick the lucky name has a null check as:
🌐
Better Programming
betterprogramming.pub › checking-for-nulls-in-java-minimize-using-if-else-edae27016474
Checking for Nulls in Java? Minimize Using “If Else” | by Itır ...
January 26, 2022 - If you are not familiar with Lombok, I highly suggest you to check it out. I personally love Lombok and it makes a developer’s life much easier :) Lets say that you have Student.javawith fields such as id, name and classes. You can use put @Builder.Default before the related field and give it a default value. When an instance of this Student class is created, it will have “classes” as an empty list, not null.
Find elsewhere
🌐
DEV Community
dev.to › scottshipp › better-null-checking-in-java-ngk
Better Null-Checking in Java - DEV Community
January 11, 2019 - Java doesn’t allow operator creation, so we can’t imitate this behavior exactly, but I have used some of the functional features found in Java 8, such as method references, to create similar functionality. Take a look. As a motivating example, finding a user’s zip code in their account might look similar to this in standard Java: That’s three null checks in the space of ten lines.
Top answer
1 of 11
125

Style 2 isn't going Java 8 enough to see the full benefit. You don't want the if ... use at all. See Oracle's examples. Taking their advice, we get:

Style 3

// Changed EmployeeServive to return an optional, no more nulls!
Optional<Employee> employee = employeeServive.getEmployee();
employee.ifPresent(e -> System.out.println(e.getId()));

Or a more lengthy snippet

Optional<Employee> employee = employeeServive.getEmployee();
// Sometimes an Employee has forgotten to write an up-to-date timesheet
Optional<Timesheet> timesheet = employee.flatMap(Employee::askForCurrentTimesheet); 
// We don't want to do the heavyweight action of creating a new estimate if it will just be discarded
client.bill(timesheet.orElseGet(EstimatedTimesheet::new));
2 of 11
50

If you're using Optional as a "compatibility" layer between an older API that may still return null, it may be helpful to create the (non-empty) Optional at the latest stage that you're sure that you have something. E.g., where you wrote:

Optional<Employee> employeeOptional = Optional.ofNullable(employeeService.getEmployee());
if(employeeOptional.isPresent()){
    Employee employeeOptional= employeeOptional.get();
    System.out.println(employee.getId());
}

I'd opt toward:

Optional.of(employeeService)                 // definitely have the service
        .map(EmployeeService::getEmployee)   // getEmployee() might return null
        .map(Employee::getId)                // get ID from employee if there is one
        .ifPresent(System.out::println);     // and if there is an ID, print it

The point is that you know that there's a non-null employee service, so you can wrap that up in an Optional with Optional.of(). Then, when you call getEmployee() on that, you may or may not get an employee. That employee may (or, possibly, may not) have an ID. Then, if you ended up with an ID, you want to print it.

There's no need to explicitly check for any null, presence, etc., in this code.

🌐
DZone
dzone.com › coding › java › java 8 optional - avoid null and nullpointerexception altogether - and keep it pretty
Java 8 Optional - Avoid Null and NullPointerException Altogether - and Keep It Pretty
September 27, 2014 - Please note that I added *Optional() methods in the types for that. There are other ways to do it (map + flatMap to Optional::ofNullable is one). The best one: only return optional value where it makes sense: if you know the value will always be provided, make it non-optional. By the way, this advice works for old style null checks too.
Top answer
1 of 11
47

If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.

2 of 11
22

Don't use null, use Optional

As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.

It's impossible to tell that could be null and what couldn't be.

Java 8 introduces a much better pattern: Optional.

And example from Oracle:

String version = "UNKNOWN";
if(computer != null) {
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null) {
    USB usb = soundcard.getUSB();
    if(usb != null) {
      version = usb.getVersion();
    }
  }
}

If each of these may or may not return a successful value, you can change the APIs to Optionals:

String name = computer.flatMap(Computer::getSoundcard)
    .flatMap(Soundcard::getUSB)
    .map(USB::getVersion)
    .orElse("UNKNOWN");

By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.

If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.

A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/


@Nonnull, @Nullable

Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.


Check when it makes sense

Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.

On the other hand, if null could be used and mean something, make sure to use it.


Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.

🌐
LabEx
labex.io › tutorials › java-how-to-check-if-an-object-is-null-in-java-560011
How to Check If an Object Is Null in Java | LabEx
In this step, we will explore a ... in Java 8: the Optional class. Optional is a container object that may or may not contain a non-null value. It provides a way to represent the presence or absence of a value more explicitly, helping to reduce the risk of NullPointerExceptions. Using Optional encourages you to think about the possibility of a value being absent and handle that case gracefully, rather than relying on null checks scattered ...
🌐
Reddit
reddit.com › r/javahelp › how and when do you guys check "null"?
r/javahelp on Reddit: How and When do you guys check "null"?
September 4, 2024 -

I'm 4 y experienced Java dev but still it's unclear how and when to check nullity sometimes and it happened today. Let's say there is a table called students and it has column called `last_name` which is not null.

create table students (
    last_name varchar(255) not null
)

You have written validation code to ensure all required column is appeared while inserting new record and there is a method that needs last_name of students. The parameter of this method may or may not come from DB directly(It could be mapped as DTO). In this case do you check nullity of `last_name` even though you wrote validation code? Or just skip the null check since it has not null constraint?

I know this depends on where and how this method is used and i skipped the null check because i think this method is not going to be used as general purpose method only in one class scope.

Top answer
1 of 6
17
I think there are a few approaches: Check everywhere. Be super defensive, and check the inputs to essentially every function for nulls and other violated invariants Define a boundary. Try to create clear "boundaries" in your code, for example by validating all external inputs in one layer, and then allowing the layers below this to assume that their inputs are valid Use types to your advantage, e.g. by having a PhoneNumber class rather than just using a String (which indicates that the phone number has been validated), or a PendingOrder and DeliveredOrder class rather than a single Order class with an isDelivered property (which prevents you from using orders in unintended ways) YOLO. Don't have a consistent approach to validating things
2 of 6
4
Ideally you write your interfaces and methods such that they don't return nulls and your objects don't have any properties set to null (so use Optional as return type where it makes sense, and/or return 'empty' objects, primitives, or throw exceptions). Personally, if I write a public method that could return 'null', I make it explicitly clear in the name itself, for example: `getStatusDetailsOrNull()` - but typically, I would return an Optional. Outside of that, you check the contract of the method. If the method does not guarantee a non-null response, then you check it. If you don't know, then you also check for non-null. Also use a good static checker, which will flag some areas where null can occur. In your example, you can enforce the DTO to never have a null value. Make it an immutable object, and guarantee that either instance creation fails, or no DTO field is ever null. You can then add a bunch of unit tests to make sure that a future developer does not break this accidentally. I'm not a huge fan of just checking for null everywhere because it does liter your code with superfluous checks, and it communicates to others that some method could be returning null (even though the contract may state that it doesn't).
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.

🌐
Coderanch
coderanch.com › t › 693624 › java › check-null-empty-strings-time
Do we have any way to check null value and empty strings all the time ? (Features new in Java 8 forum at Coderanch)
For example, if you have a Person class you can design it like this:-...or like this:-If I go into the first class, what are you going to do about the middle name I haven't got? Mark it null? But in the second version, you can have an array with all middle names in; in my case you can use a zero‑length array. Abracadabra! No nulls More details in books like Effective Java by Joshua Bloch.