DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Containers Trend Report: Explore the current state of containers, containerization strategies, and modernizing architecture.

Low-Code Development: Learn the concepts of low code, features + use cases for professional devs, and the low-code implementation process.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Java String: A Complete Guide With Examples
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Import a Function/Module in Dataweave
  • Deploying Artemis Broker With SSL Enabled and Use AMQP

Trending

  • Kubernetes DaemonSet: Practical Guide to Monitoring in Kubernetes
  • CI/CD Metrics You Should Be Monitoring
  • Why Understanding Kubernetes Costs Is Crucial To Growing Our Business
  • 7 Technical Reasons Why Software Product Engineering Projects Fail
  1. DZone
  2. Coding
  3. Java
  4. Java 8 Elvis Operator

Java 8 Elvis Operator

So when I heard about a new feature in Java 8 that was supposed to help mitigate bugs, I was excited.

Robert Greathouse user avatar by
Robert Greathouse
·
May. 06, 14 · News
Like (5)
Save
Tweet
Share
77.1K Views

Join the DZone community and get the full member experience.

Join For Free

DISCLAIMER: This post contains a rant. Reader discretion is advised.

Null pointers are the bane of software developers. The nefarious NullPointerException or NoReferenceException is know to all Java or C# developers. At best, they are a minor inconvenience. At worst, they can cost companies a lot of money. So when I heard about a new feature in Java 8 that was supposed to help mitigate these bugs, I was excited.

The feature is called “Optional”. There are a lot of existing examples in other languages of how nulls can be easily handled. Indeed, the documentation even cites some of the examples.

What Alternatives to Null Are There?
Languages such as Groovy have a safe navigation operator represented by “?.” to safely navigate through potential null references. (Note that it is soon to be included in C#, too, and it was proposed for Java SE 7 but didn’t make it into that release.) It works as follows:

String version = computer?.getSoundcard()?.getUSB()?.getVersion();

In this case, the variable version will be assigned to null if computer is null, or getSoundcard() returns null, or getUSB() returns null. You don’t need to write complex nested conditions to check for null.

In addition, Groovy also includes the Elvis operator “?:” (if you look at it sideways, you’ll recognize Elvis’ famous hair), which can be used for simple cases when a default value is needed. In the following, if the expression that uses the safe navigation operator returns null, the default value “UNKNOWN” is returned; otherwise, the available version tag is returned.

String version = computer?.getSoundcard()?.getUSB()?.getVersion() ?: “UNKNOWN”;

[snip]

OK, we diverged a bit and all this sounds fairly abstract. You might now wonder, “so, what about Java SE 8?”

After reading that section, I was momentarily excited. The “?” and “?:” operators in groovy are godsends. But, my enthusiasm was quickly halted. To use this new feature, variables have to be wrapped in Optional objects. For instance:

public Optional<Book> findBook(String isbn) {
   Book b = //look up book in some repository that may return "null" for not found
   return Optional.ofNullable(b);
}

So what does the equivalent Elvis operator “?:” look like in Java 8?

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

What happened here? How can you tease me with the easy to use syntax and then throw this up? What the heck is flatMap and map? All I’m trying to do is get the version of the usb connected to the soundcard on my computer.

I can see where there are other use cases for Optional as I read through the rest of the documentation page. But I have to wonder if those other features could have somehow been tacked onto the language in a different manner. I fully admit that I am not a language creator, nor have any experience in it. But in APIs that I write, I try to hide away the ugly and leave a nice, easy-to-use front end. The above does not appear to hide the ugly.

To be fair, I have not had any practical experience with the new features in Java 8. So it is possible I do not fully understand how this particular feature will fit in with the new additions. I will keep an open mind and attempt to use the Optional feature when it makes sense. I tend to write mostly in groovy thesedays, so I will happily keep using the “?” an “?:” operators.

Thanks for reading my rant.

Operator (extension) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Java String: A Complete Guide With Examples
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Import a Function/Module in Dataweave
  • Deploying Artemis Broker With SSL Enabled and Use AMQP

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: