Java
Programming
Null Values
Java Tips
Coding Best Practices

How to get the first non-null value in Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Java, handling null values efficiently is a common challenge that developers face, particularly when dealing with potentially null objects. This can occur often in data retrieval processes from databases or external APIs. Retrieving the first non-null value can prevent null pointer exceptions and ensure smooth program operation. This article will guide you through different approaches to achieve this functionality utilizing Java's features.

Understanding Null Safety in Java

Java's type system doesn't inherently prevent null pointer exceptions, unlike some modern languages which have built-in null safety. Thus, developers must explicitly check and handle potential null values. Here are several strategies you can employ to retrieve the first non-null value in Java.

Utilizing Ternary Operator

The ternary operator (? :) offers a concise way for null checking. This can be useful when you need to check a small number of variables:

java
1String value1 = null;
2String value2 = "Hello";
3
4String result = (value1 != null) ? value1 : (value2 != null) ? value2 : "Default Value";
5System.out.println(result);  // Output: Hello

Using Streams API

Introduced in Java 8, the Streams API provides an expressive way to process sequences of elements. It can be employed to find the first non-null value in a collection.

java
1import java.util.stream.Stream;
2
3public class FirstNonNullExample {
4    public static void main(String[] args) {
5        String value1 = null;
6        String value2 = null;
7        String value3 = "Hello";
8
9        String result = Stream.of(value1, value2, value3)
10                .filter(item -> item != null)
11                .findFirst()
12                .orElse("Default Value");
13
14        System.out.println(result);  // Output: Hello
15    }
16}

Employing Optional Class

The Optional class, another feature from Java 8, is specifically designed to handle cases that might result in null values.

java
1import java.util.Optional;
2
3public class FirstNonNullUsingOptional {
4    public static void main(String[] args) {
5        String value1 = null;
6        String value2 = "Hello";
7        String value3 = null;
8
9        String result = Optional.ofNullable(value1)
10                .or(() -> Optional.ofNullable(value2))
11                .or(() -> Optional.ofNullable(value3))
12                .orElse("Default Value");
13
14        System.out.println(result);  // Output: Hello
15    }
16}

ConditionalExpressions Using If-Else Blocks

If handling many variables or requiring complex logic, traditional if-else blocks can be more readable than chained ternaries.

java
1public class FirstNonNullIfElse {
2    public static void main(String[] args) {
3        String value1 = null;
4        String value2 = "Hello";
5        String value3 = null;
6
7        String result;
8
9        if (value1 != null) {
10            result = value1;
11        } else if (value2 != null) {
12            result = value2;
13        } else if (value3 != null) {
14            result = value3;
15        } else {
16            result = "Default Value";
17        }
18
19        System.out.println(result);  // Output: Hello
20    }
21}

Key Methods Summary

ApproachDescriptionSuitable For
Ternary OperatorConcise check using ?:. Best for short conditions.Smaller number of variables.
Streams APIUses filter and findFirst methods.Working with collections or arrays.
Optional ClassUses Optional.ofNullable and or for chaining.When leveraging Optional might use existing data flow.
If-Else BlocksUses traditional conditionals for handling null check sequences.Complex or lengthy checks.

Conclusion

In Java, the approach you choose to retrieve the first non-null value largely depends on the context and specific requirements. For examples where readability and conciseness are crucial, Streams or Optional can offer elegant solutions. For straightforward or smaller checks, the ternary operator might be preferred, while complex conditions may be better served with if-else blocks.

Each tool has its strengths, and understanding these options will empower you to write clearer, more efficient, and safer Java code.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.