Home » JVM Languages » Groovy » Avoid NullPointerException: Safe Navigation with Groovy

About Ted Vinke

Ted Vinke
Ted is a Java software engineer with a passion for Web development and JVM languages and works for First8, a Java Web development company in the Netherlands.

Avoid NullPointerException: Safe Navigation with Groovy

We know it’s all too common in Java to get a NullPointerException when we use an object reference which is null. This happens when our code tries to access a method or field of an object, or element of an array when there’s no instance present – e.g. it refers to null.

class Animal {
 String name
 Animal parent

def animal = new Animal(name: "Bella") // no parent

We might get an Animal instance from the outside and we need to get the name of the parent.

def parentName = animal.parent.name
// BLAM! java.lang.NullPointerException: 
// Cannot get property 'name' on null object

Parent is null. Usually as a precaution we have to check for null beforehand.

if (animal.parent != null) {
 def parentName = animal.parent.name

You can see that if we need the name of the grandparent, there are even more references which could be null.

def grandParentName = animal.parent.parent.name

We need a safe way to navigate through references we might expect to be null. Fortunately, with Groovy this is very easy. Use the Safe Navigation (or null-safe) operator which guards against NullPointerExceptions. This is just a question mark (?) before the dot (.)


A small little gem, but a great feature of Groovy.

// instead of checking for nulls the Java way
if (animal.parent != null && animal.parent.parent != null) {
 def grandParentName = animal.parent.parent.name

// or using the Groovy truth
if (animal.parent && animal.parent.parent) {
 def grandParentName = animal.parent.parent.name

// use safe navigation
def grandParentName = animal.parent?.parent?.name

// and in combination with Elvis
grandParentName = animal.parent?.parent?.name ?: "Unknown"
(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments