DEV Community

DEV Community

scottshipp

Posted on Jan 11, 2019

Better Null-Checking in Java

Photo by Estée Janssens on Unsplash

Java runs some of the largest sites and platforms in the world but I’ve often struggled with its design as a language.

And yet it’s a great language for getting things done. I’ve put Java into production where it handles thousands of requests per second while working at companies like Expedia and OpenMarket . The Java compiler, as well as excellent developer tooling in a strong ecosystem surrounding the language, prevents whole classes of application errors.

Too bad, then, that the most common failure seen in a Java application is the NullPointerException. A NullPointerException is thrown whenever the JVM attempts to dereference a variable and finds null instead of an object. How can you prevent that? The answer is easy: just don’t have any variables pointing to null.

Unfortunately, Java is a nasty language that practically forces the programmer into creating (or receiving through method parameters) variables referencing null. Any declared but uninitialized variable automatically references null, and other Java language constructs like try/catch force variables to have to be declared in an outer scope where null is one of the only valid choices.

Here’s a common example, from one of the official Java tutorials , which is considered good Java:

If there were other code that used the out variable later, it would have to perform null-checking (as seen in line 19) again. If out is used frequently, the application might be littered with null-checking.

Workarounds

I have what I think is a solution but I want to briefly mention a couple of the existing ways of handling it, and why I think we still need something else.

Option 1: don’t null check.

One school of thought is just don’t null check. Let the NullPointerException happen.Then take steps to remedy the underlying cause. Robert Brautingham’s Why I Never Null Check Parameters is an example of this philosophy.

I of course agree with this school of thought when it’s actually possible to solve the underlying cause. Unfortunately, I believe that there are plenty of times where the actual language forces null-checking on the programmer. And if the language doesn’t, someone else’s library does.

Photo by Marvin Meyer on Unsplash

Option 2: use Optional.

Another option (ha ha, get it) is to use the Optional class introduced in Java 8. Baeldung’s Guide to Java 8 Optional covers the usage well. Great idea, honestly, if the code in question is handling a Stream. That’s kind of what Optional was made for and if you have the option (ok, ok, I know this is getting a little heavy-handed) go for it.

What I have found, though, is that there are plenty of situations where awkward null-checking has been replaced with still-awkward usage of Optional, such as this example from a popular open-source Java tool:

That’s really no different than the null-check in this twin code:

Examples like these have led a lot of the Java community to declare that Optional.get is a Code Smell .

A Better Way

Other languages like Groovy and C# have a nice null-conditional operator that allows the programmer to specify that a chain of references might contain a null somewhere along the way, and a natural way to deal with that is to just short-circuit the chain of calls and result in a null value.

Here’s the first example from the C# documentation:

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.

Using my solution, which I’ve released as part of a library called Mill, the motivating example can be converted to:

There would then be a single null check afterward. Or, if an empty string or another default value might be more applicable, there is an alternative getOrDefault() method. There’s also a getOrThrow() method for when an exception is more appropriate.

Photo by Tanguy Sauvin on Unsplash

Mill is made available under the MIT license, so you’re free to grab the jar and put it on your application’s classpath. Mill also has a number of useful stream-related features that can make streams more fluent and readable.

And if you’re the type to contribute, Mill is open to contributions. The repository is available on Github . I’m thinking about getting it distributed so that it’s easy to add to a Maven or Gradle file. But, all things in due time, and with the right help.

A Postscript

I’m sure that as long as Java lives there will be null-checking in Java code. The question is can we do better than what standard Java allows? I believe the answer is yes, we can and I hope that by combining some of the various approaches mentioned in this article, including Mill’s NullSafe class, we can continue to make our application code more elegant and prevent more NullPointerExceptions in Java applications.

scottashipp / mill

Java library to make run-of-the-mill tasks more elegant. compatible with java 8+..

logo

Java library to make run-of-the-mill tasks more elegant.

Note: This library is deprecated.

Update March, 2020. I will no longer be maintaining Mill. There are now other libraries with more widespread adoption and some actual funding and a set of active maintainers. (See StreamEx ).

In addition, Mill is now the name of a build tool for Java and Scala.

Nevertheless, it is still useful at providing some examples of the things you can add to your own codebase to improve working with Java streams or lambdas.

Compatible with Java 8+.

In this README

How to add mill to your application.

  • Some examples
  • Contribution guidelines
  • Where to find help

If you are using Maven or another supported dependency management tool, you can use Jitpack to add Mill to your application.

First, add Jitpack (if you haven't already) to the repositories…

Top comments (13)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

evanoman profile image

  • Email [email protected]
  • Location Minnesota
  • Education Masters in Applied Math
  • Work Software Engineer at Black River Systems Co.
  • Joined May 24, 2017

How is your Nullable example different than using Option.ofNullable ?

Ahh, I missed the intermediary null checks, this is more accurate:

goyo profile image

  • Location Barcelona
  • Work Switching Jobs Soon
  • Joined Jun 22, 2017

No, you didn’t. You can do it exactly as in your first example.

redaalaoui profile image

  • Joined Jun 18, 2017

I confirm, the first example works.

But besidd that, this goes against rule of Demeter.

You should not have to access so many indirect attributes to get the zip code. User should expose a getZipCode method.

ernir profile image

  • Joined Jan 12, 2019

Tip: the first case, where null checks are used to handle resources, can usually be avoided by using a try-with-resources statement, available since Java 7. An example is available in the preceding section of the Java tutorial that is linked.

ondrejs profile image

  • Location .onion
  • Joined Oct 25, 2018

Nice post, mill is IMHO super useful library for Java programmers (for those who did not switch to Kotlin yet or maintaining legacy code written in Java :)).

jbristow profile image

  • Location San Diego
  • Work Staff DevSecOps Engineer
  • Joined Mar 12, 2017

I’m of the opinion that if you can’t sell switching to Haskell, then push for kotlin. It just makes writing JVM code more sane.

The only wackiness comes when you run into a library that is cheating with reflection to overcome the lack of sum or product types in Java. (I’M LOOKING AT YOU , GREMLIN!)

Ha, nice point, Jon,

to be fair, I have to admit that I'm Kotlin enthusiast...but still write much of my code in Java because of.....just because. I have a reasons for it.

_hs_ profile image

  • Location Göteborg, Sweden
  • Work Software developer
  • Joined Jul 26, 2018

And why not Groovy or Scala instead of Kotlin? TIOBE index shows Groovy(17 today used to be way below) getting way above Kotlin nowadays while the Kotlin gets lower (39 used to be about 35 I think).

Also I played with Kotiln and dislike it as do some other people that use JVM stuff not only me, so why would you assume Kotlin would be better choice?

I really need someone to explain to me what's so great about this language that Groovy or Scala couldn't provide. The only thing is Google and Android in my opinion.

Nice lib. I do miss ?. and ?? from C# in Java. But I also miss Micronaut/Spring in C# so it's a no brainer :D. Although good thing about JVM frameworks I can combine Groovy and Kotlin with Java to make some stuff have those operators :D.

byelaw profile image

  • Joined Apr 9, 2024

One way of handling nulls which wasn't discussed is to use the following statics used to check objects before operating on them:

I use them early to fail fast if need be, and we can learn more about the exception by adding a second parameter to Objects.requireNonNull to give context.

docs.oracle.com/javase%2F9%2Fdocs%...

There are also the many @notnull annotations available from various libraries such as Spring.

gustavo94 profile image

  • Email [email protected]
  • Location Medellín, Colombia
  • Education Software Engineer
  • Work Software Developer at S4N
  • Joined Mar 31, 2017

I want to recommend you to look at Option<> monad in VAVR it's behavior is similar to the example of NullSafe.

qew7 profile image

  • Joined Feb 22, 2017

What bout null object pattern?

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

SOLID Principles Explained (with examples in Java)

rachel - May 2

tanujav profile image

Count Good Nodes in Binary Tree | LeetCode | Java

Tanuja V - May 2

kailashnirmal profile image

JP Morgan Interview Question & Answers | Java Developer 7+ Years Experience for Mumbai

Kailash Nirmal - May 2

paulike profile image

Generating Random Numbers

Paul Ngugi - May 2

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

DZone

  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
  • Manage My Drafts

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

Feeling secure? Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns : Explore key traits of migrating open-source software and its impact on software development.

  • Twenty Things Every Java Software Architect Should Know
  • Java 8 Threading and Executor Services
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • How To Compare DOCX Documents in Java
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Data Analysis and Automation Using Python
  • Optimizing InfiniBand Bandwidth Utilization for NVIDIA DGX Systems Using Software RAID Solutions
  • Spring AI: How To Write GenAI Applications With Java

Java 8 Optional: Handling Nulls Properly

Let's learn how to use java 8's optionals to make your null checks simple and less error-prone.

Yogen Rai user avatar

Join the DZone community and get the full member experience.

Java 8 introduced the  Optional class to make handling of nulls less error-prone. For example, the following program to pick the lucky name has a null check as:

This null check can be replaced with the  Optional   class method  isPresent()    as shown below:

However, notice the writing is no easier than:

The  Optional   class, however, supports other techniques that are superior to checking nulls. The above code can be re-written as below with   orElse()   method as below:

The method  orElse()   is invoked with the condition " If X is null, populate X. Return X. ", so that the default value can be set if the optional value is not present.

There is another method called the  ifPresent(Function) . You can use this method to invoke an action and skip the null case completely. For example, the program below prints a message in the case, if the condition is met as:

This can be re-written with  ifPresent()  ,  as shown below. in a more intuitive manner, as:

If we want to throw an exception in case if no name is found, then it would be something like this:

It can be meaningfully replaced with  orElseThrow   as:

There are other many more methods in the  Optional   class to handle  null   in more proper way. You can go through the  Optional in Java 8 cheat sheet .

As always, if you want to look into the source code for the example presented above, they are available on  GitHub .

Opinions expressed by DZone contributors are their own.

Partner Resources

  • About DZone
  • Send feedback
  • Community research
  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone
  • Terms of Service
  • Privacy Policy
  • 3343 Perimeter Hill Drive
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

In software development, null values can be a frequent source of bugs and errors, especially in languages like Java that use explicit references. Null values occur when an object reference does not refer to an instance of an object, but rather to a special value that represents the absence of a value. In Java 8, there are several ways to check for null values to avoid these bugs.

The traditional approach to checking for null values in Java is to use the == operator to compare the reference to null. Here's an example:

This approach is straightforward but can be verbose and error-prone, especially when multiple null checks are required. Additionally, it is not very expressive and does not take advantage of some of the new language features introduced in Java 8.

Java 8 introduced the Optional class as a way to handle null values more effectively. Optional is a container object that may or may not contain a non-null value. Optional provides a number of methods to work with the contained value, such as map(), filter(), and orElse(). Here's an example:

This approach is more concise and expressive than the traditional null check. It also provides a more functional programming style by allowing the use of methods such as map() and filter().

Another way to check for null values in Java 8 is to use the Objects.requireNonNull() method. This method throws a NullPointerException if the passed reference is null. Here's an example:

This approach is even more concise than the Optional class, as it doesn't require an if statement. However, it can be less expressive than the Optional class because it does not provide any methods to work with the non-null value.

In addition to the three approaches mentioned above, there are a few other techniques that can be used to handle null values in Java 8.

Java 8 also introduced the Objects.isNull() and Objects.nonNull() methods. These methods provide a more concise way to check for null values than the traditional null check. Here's an example:

The approach is similar to the traditional null check, but provides a more concise syntax.

The Optional class also provides the map() method, which can be used to transform the contained value if it is not null. This can be useful for chaining multiple operations together. Additionally, the orElseThrow() method can be used to throw an exception if the contained value is null. Here's an example:

This approach uses the map() method to extract a property from the non-null object, and then uses orElseThrow() to handle the case where the object is null.

Finally, Java 9 introduced the Objects.requireNonNullElse() method. This method can be used to provide a default value if the passed reference is null. Here's an example:

This approach provides a concise way to handle null values and can be useful in situations where a default value is needed.

Java 8 provides several ways to check for null values, each with its own advantages and disadvantages. Developers should choose the approach that best fits their needs based on factors such as code readability, maintainability, and performance. By using these techniques, developers can avoid null-related bugs and improve the quality and reliability of their Java applications.

Here's an example program that demonstrates how to use the Optional class to check for null values in Java 8:





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The Complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works - JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted Output in Java using printf()
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples

Java Assignment Operators with Examples

  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • 'this' reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Singleton Method Design Pattern in Java
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Java Try Catch Block
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • Regex Tutorial - How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Difference Between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

JDBC - Java Database Connectivity

  • Introduction to JDBC (Java Database Connectivity)
  • JDBC Drivers
  • Establishing JDBC Connection in Java
  • Types of Statements in JDBC
  • JDBC Tutorial
  • Java 8 Features - Complete Tutorial

Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide.

Types of Operators: 

  • Arithmetic Operators
  • Unary Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators

This article explains all that one needs to know regarding Assignment Operators. 

Assignment Operators

These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. This means that the assignment operators have right to left associativity, i.e., the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is, 

Types of Assignment Operators in Java

The Assignment Operator is generally of two types. They are:

1. Simple Assignment Operator: The Simple Assignment Operator is used with the “=” sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

2. Compound Assignment Operator: The Compound Operator is used where +,-,*, and / is used along with the = operator.

Let’s look at each of the assignment operators and how they operate: 

1. (=) operator: 

This is the most straightforward assignment operator, which is used to assign the value on the right to the variable on the left. This is the basic definition of an assignment operator and how it functions. 

Syntax:  

Example:  

2. (+=) operator: 

This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

Note: The compound assignment operator in Java performs implicit type casting. Let’s consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5 Method 2: x += 4.5 As per the previous example, you might think both of them are equal. But in reality, Method 1 will throw a runtime error stating the “i ncompatible types: possible lossy conversion from double to int “, Method 2 will run without any error and prints 9 as output.

Reason for the Above Calculation

Method 1 will result in a runtime error stating “incompatible types: possible lossy conversion from double to int.” The reason is that the addition of an int and a double results in a double value. Assigning this double value back to the int variable x requires an explicit type casting because it may result in a loss of precision. Without the explicit cast, the compiler throws an error. Method 2 will run without any error and print the value 9 as output. The compound assignment operator += performs an implicit type conversion, also known as an automatic narrowing primitive conversion from double to int . It is equivalent to x = (int) (x + 4.5) , where the result of the addition is explicitly cast to an int . The fractional part of the double value is truncated, and the resulting int value is assigned back to x . It is advisable to use Method 2 ( x += 4.5 ) to avoid runtime errors and to obtain the desired output.

Same automatic narrowing primitive conversion is applicable for other compound assignment operators as well, including -= , *= , /= , and %= .

3. (-=) operator: 

This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting the variable’s value on the right from the current value of the variable on the left and then assigning the result to the operand on the left. 

4. (*=) operator:

 This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

5. (/=) operator: 

This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the quotient to the operand on the left. 

6. (%=) operator: 

This operator is a compound of ‘%’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the remainder to the operand on the left. 

Please Login to comment...

Similar reads.

  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Java Tutorial
  • What is Java?
  • Installing the Java SDK
  • Your First Java App
  • Java Main Method
  • Java Project Overview, Compilation and Execution
  • Java Core Concepts
  • Java Syntax
  • Java Variables
  • Java Data Types
  • Java Math Operators and Math Class
  • Java Arrays
  • Java String
  • Java Operations
  • Java if statements

Java Ternary Operator

  • Java switch Statements
  • Java instanceof operator
  • Java for Loops
  • Java while Loops
  • Java Classes
  • Java Fields
  • Java Methods
  • Java Constructors
  • Java Packages
  • Java Access Modifiers
  • Java Inheritance
  • Java Nested Classes
  • Java Record
  • Java Abstract Classes
  • Java Interfaces
  • Java Interfaces vs. Abstract Classes
  • Java Annotations
  • Java Lambda Expressions
  • Java Modules
  • Java Scoped Assignment and Scoped Access
  • Java Exercises

Java Ternary Operator Video Tutorial

Ternary operator condition, ternary operator values, ternary operator as null check, ternary operator as type check, ternary operator as max function, ternary operator as min function, ternary operator as abs function, chained ternary operators.

Jakob Jenkov
Last update: 2024-05-12

The Java ternary operator functions like a simplified Java if statement. The ternary operator consists of a condition that evaluates to either true or false , plus a value that is returned if the condition is true and another value that is returned if the condition is false . Here is a simple Java ternary operator example:

We will dissect this ternary operator example in the rest of this Java ternary operator tutorial.

In case you prefer video, I have a video version of this tutorial here:

The ternary operator part of the above statement is this part:

The condition part of the above ternary operator expression is this part:

The condition is a Java expression that evaluates to either true or false . The above condition will evaluate to true if the case variable equals the Java String value uppercase , and to false if not.

The condition can be any Java expression that evaluates to a boolean value, just like the expressions you can use inside an if - statement or while loop.

The condition part of a ternary operator is followed by a question mark ( ? ). After the question mark are the two values the ternary operator can return, separated by a colon ( : ). The values part of the ternary operator shown earlier is:

The values part consists of two values. The first value is returned if the condition parts (see above) evaluates to true . The second value is returned if the condition part evaluates to false .

In the example above, if case.equals("uppercase") evaluates to true then the ternary operator expression as a whole returns the String value JOHN . If case.equals("uppercase") evaluates to false then the ternary operator expression as a whole returns the String value john . That means, that the String variable name will end up having the value JOHN or john depending on whether the expression case.equals("uppercase") evaluates to true or false .

The values returned can be the result of any Java expression that returns a value that can be assigned to the variable at the beginning of the statement. Because the Java variable at the beginning of the ternary operator example at the top of this article is of type String, then the values returned by the values part must be of type String.

You can use the Java ternary operator as a shorthand for null checks before calling a method on an object. Here is an example:

This is equivalent to, but shorter than this code:

As you can see, both of these code examples avoid calling object.getValue() if the object reference is null , but the first code example is a bit shorter and more elegant.

It is also possible to use the Java ternary operator as a type check. Here is an example of using the Java ternary operator as a type check:

Notice how the example uses two ternary operator statements after each other. The first checks if the object returned by the getTheObject() method is an instance of Integer or Long, and then casts the theObj reference to either Integer or Long, and call either the intValue() or longValue()

You can achieve the same functionality as the Java Math max() function using a Java ternary operator. Here is an example of achieving the Math.max() functionality using a Java ternary operator:

Notice how the ternary operator conditions checks if the val1 value is larger than or equal to the val2 value. If it is, the ternary operator returns the val1 value. Else it returns the val2 value.

The Java ternary operator can also be used to achieve the same effect as the Java Math min() function . Here is an example of achieving the Math.min() functionality using a Java ternary operator:

Notice how the ternary operator conditions checks if the val1 value is smaller than or equal to the val2 value. If it is, the ternary operator returns the val1 value. Else it returns the val2 value.

The Java ternary operator can also be used to achieve the same effect as the Java Math abs() function . Here is an example of achieving the Math.abs() functionality using a Java ternary operator:

Notice how the ternary operator conditions checks if the val1 value is larger than or equal to 0. If it is, the ternary operator returns the val1 value. Else it returns -val1 , which corresponds to negating a negative number, which makes it positive.

It is possible to chain more than one Java ternary operator together. You do so by having one of the values returned by the ternary operator be another ternary operator. Here is an example of a chained ternary operator in Java:

Notice how the first ternary operator condition checks if the input String is null . If so, the first ternary operator returns 0 immediately. If the input String is not null , the first ternary operator returns the value of the second ternary operator. The second ternary operator checks if the input String is equal to the empty String. If it is, the second ternary operator returns 0 immediately. If the input String is not equal to the empty String, the second ternary operator returns the value of Integer.parseInt(input) .

You can chain and nest Java ternary operators as much as you want, as long as each ternary operator returns a single value, and each ternary operator is used in place of a single value (the Java ternary operator is an expression, and is thus evaluated to a single value).

Of course you could have simplified the above ternary operator example. Instead of chaining the ternary operators you could have combined the two conditions that return 0 into a single condition, like this:

However, this is only possible because the value null and empty string both return the same value (0). Anyways, the point was to show you how to chain the Java ternary operator . That is why the example was written the way it was.

Jakob Jenkov

Java ForkJoinPool

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Expressions and operators

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely evaluate .

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to 7 .

The expression 3 + 4 is an example of the second type. This expression uses the + operator to add 3 and 4 together and produces a value, 7 . However, if it's not eventually part of a bigger construct (for example, a variable declaration like const z = 3 + 4 ), its result will be immediately discarded — this is usually a programmer mistake because the evaluation doesn't produce any effects.

As the examples above also illustrate, all complex expressions are joined by operators , such as = and + . In this section, we will introduce the following operators:

Assignment operators

Comparison operators, arithmetic operators, bitwise operators, logical operators, bigint operators, string operators, conditional (ternary) operator, comma operator, unary operators, relational operators.

These operators join operands either formed by higher-precedence operators or one of the basic expressions . A complete and detailed list of operators and expressions is also available in the reference .

The precedence of operators determines the order they are applied when evaluating an expression. For example:

Despite * and + coming in different orders, both expressions would result in 7 because * has precedence over + , so the * -joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a grouped expression — the basic expression). To see a complete table of operator precedence as well as various caveats, see the Operator Precedence Reference page.

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3 + 4 or x * y . This form is called an infix binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x . The operator operand form is called a prefix unary operator, and the operand operator form is called a postfix unary operator. ++ and -- are the only postfix operators in JavaScript — all other operators, like ! , typeof , etc. are prefix.

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Name Shorthand operator Meaning

Assigning to properties

If an expression evaluates to an object , then the left-hand side of an assignment expression may make assignments to properties of that expression. For example:

For more information about objects, read Working with Objects .

If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:

In strict mode , the code above throws, because one cannot assign properties to primitives.

It is an error to assign values to unmodifiable properties or to properties of an expression without properties ( null or undefined ).

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

Without destructuring, it takes multiple statements to extract values from arrays and objects:

With destructuring, you can extract multiple values into distinct variables using a single statement:

Evaluation and nesting

In general, assignments are used within a variable declaration (i.e., with const , let , or var ) or as standalone statements.

However, like other expressions, assignment expressions like x = f() evaluate into a result value. Although this result value is usually not used, it can then be used by another expression.

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, some JavaScript style guides discourage chaining or nesting assignments . Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.

By chaining or nesting an assignment expression, its result can itself be assigned to another variable. It can be logged, it can be put inside an array literal or function call, and so on.

The evaluation result matches the expression to the right of the = sign in the "Meaning" column of the table above. That means that x = f() evaluates into whatever f() 's result is, x += f() evaluates into the resulting sum x + f() , x **= f() evaluates into the resulting power x ** f() , and so on.

In the case of logical assignments, x &&= f() , x ||= f() , and x ??= f() , the return value is that of the logical operation without the assignment, so x && f() , x || f() , and x ?? f() , respectively.

When chaining these expressions without parentheses or other grouping operators like array literals, the assignment expressions are grouped right to left (they are right-associative ), but they are evaluated left to right .

Note that, for all assignment operators other than = itself, the resulting values are always based on the operands' values before the operation.

For example, assume that the following functions f and g and the variables x and y have been declared:

Consider these three examples:

Evaluation example 1

y = x = f() is equivalent to y = (x = f()) , because the assignment operator = is right-associative . However, it evaluates from left to right:

  • The y on this assignment's left-hand side evaluates into a reference to the variable named y .
  • The x on this assignment's left-hand side evaluates into a reference to the variable named x .
  • The function call f() prints "F!" to the console and then evaluates to the number 2 .
  • That 2 result from f() is assigned to x .
  • The assignment expression x = f() has now finished evaluating; its result is the new value of x , which is 2 .
  • That 2 result in turn is also assigned to y .
  • The assignment expression y = x = f() has now finished evaluating; its result is the new value of y – which happens to be 2 . x and y are assigned to 2 , and the console has printed "F!".

Evaluation example 2

y = [ f(), x = g() ] also evaluates from left to right:

  • The y on this assignment's left-hand evaluates into a reference to the variable named y .
  • The function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 result from g() is assigned to x .
  • The assignment expression x = g() has now finished evaluating; its result is the new value of x , which is 3 . That 3 result becomes the next element in the inner array literal (after the 2 from the f() ).
  • The inner array literal [ f(), x = g() ] has now finished evaluating; its result is an array with two values: [ 2, 3 ] .
  • That [ 2, 3 ] array is now assigned to y .
  • The assignment expression y = [ f(), x = g() ] has now finished evaluating; its result is the new value of y – which happens to be [ 2, 3 ] . x is now assigned to 3 , y is now assigned to [ 2, 3 ] , and the console has printed "F!" then "G!".

Evaluation example 3

x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For more information about objects, read Working with Objects .)

  • The x in this property access evaluates into a reference to the variable named x .
  • Then the function call f() prints "F!" to the console and then evaluates to the number 2 .
  • The x[f()] property access on this assignment has now finished evaluating; its result is a variable property reference: x[2] .
  • Then the function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 is now assigned to x[2] . (This step will succeed only if x is assigned to an object .)
  • The assignment expression x[f()] = g() has now finished evaluating; its result is the new value of x[2] – which happens to be 3 . x[2] is now assigned to 3 , and the console has printed "F!" then "G!".

Avoid assignment chains

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, chaining assignments in the same statement is discouraged .

In particular, putting a variable chain in a const , let , or var statement often does not work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are not declared by the const / let / var statement. For example:

This statement seemingly declares the variables x , y , and z . However, it only actually declares the variable z . y and x are either invalid references to nonexistent variables (in strict mode ) or, worse, would implicitly create global variables for x and y in sloppy mode .

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Comparison operators
Operator Description Examples returning true
( ) Returns if the operands are equal.

( ) Returns if the operands are not equal.
( ) Returns if the operands are equal and of the same type. See also and .
( ) Returns if the operands are of the same type but not equal, or are of different type.
( ) Returns if the left operand is greater than the right operand.
( ) Returns if the left operand is greater than or equal to the right operand.
( ) Returns if the left operand is less than the right operand.
( ) Returns if the left operand is less than or equal to the right operand.

Note: => is not a comparison operator but rather is the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations ( + , - , * , / ), JavaScript provides the arithmetic operators listed in the following table:

Arithmetic operators
Operator Description Example
( ) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
( ) Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4.
( ) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2.
( ) Unary operator. Returns the negation of its operand. If is 3, then returns -3.
( ) Unary operator. Attempts to , if it is not already.

returns .

returns .

( ) Calculates the to the power, that is, returns .
returns .

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Operator Usage Description
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Returns a zero in each bit position for which the corresponding bits of both operands are zeros.
Returns a zero in each bit position for which the corresponding bits are the same. [Returns a one in each bit position for which the corresponding bits are different.]
Inverts the bits of its operand.
Shifts in binary representation bits to the left, shifting in zeros from the right.
Shifts in binary representation bits to the right, discarding bits shifted off.
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer: Before: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001 After: 1010 0000 0000 0000 0110 0000 0000 0001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Expression Result Binary Description

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation). ~x evaluates to the same value that -x - 1 evaluates to.

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of either type Number or BigInt : specifically, if the type of the left operand is BigInt , they return BigInt ; otherwise, they return Number .

The shift operators are listed in the following table.

Bitwise shift operators
Operator Description Example

( )
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

Logical operators
Operator Usage Description
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns .
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns .
( ) Returns if its single operand that can be converted to ; otherwise, returns .

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

Note that for the second case, in modern code you can use the Nullish coalescing operator ( ?? ) that works like || , but it only returns the second expression, when the first one is " nullish ", i.e. null or undefined . It is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too.

Most operators that can be used between numbers can be used between BigInt values as well.

One exception is unsigned right shift ( >>> ) , which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".

BigInts and numbers are not mutually replaceable — you cannot mix them in calculations.

This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.

You can compare BigInts with numbers.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. It is regarded bad style to use it elsewhere, when it is not necessary. Often two separate statements can and should be used instead.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object's property. The syntax is:

where object is the name of an object, property is an existing property, and propertyKey is a string or symbol referring to an existing property.

If the delete operator succeeds, it removes the property from the object. Trying to access it afterwards will yield undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

Since arrays are just objects, it's technically possible to delete elements from them. This is, however, regarded as a bad practice — try to avoid it. When you delete an array property, the array length is not affected and other elements are not re-indexed. To achieve that behavior, it is much better to just overwrite the element with the value undefined . To actually manipulate the array, use the various array methods such as splice .

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them to avoid precedence issues.

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string, numeric, or symbol expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

Basic expressions

All operators eventually operate on one or more basic expressions. These basic expressions include identifiers and literals , but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it to the form element, as in the following example:

Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Java - variable Declaration, Assignment and null-check in a single statement

I was wondering if there is a way to make the first two lines of the following code a one-liner in Java, so that object is declared, assigned and null checked in one line:

  • if-statement

Alexander Ivanchenko's user avatar

  • 2 what do you want to do in your second line? it is just a condition. for that, it needs to be a statement –  user404 Commented Apr 19, 2022 at 17:52
  • 1 Object object = queue.poll(); if (object != null) { whatever } - Java does not require line feeds –  user16320675 Commented Apr 19, 2022 at 17:59
  • @reveance Do you need this variable to be accessible somewhere else in the code or not? –  Alexander Ivanchenko Commented Apr 19, 2022 at 18:09
  • @AlexanderIvanchenko No, just in the scope of the if block –  reveance Commented Apr 19, 2022 at 18:20
  • @user16320675 Or maybe simply allow declaration in the if statement. Is there a reason not to: if((Object object = queue.poll()) != null) { ... } ? –  reveance Commented Apr 19, 2022 at 18:24

4 Answers 4

If you don't mind having the scope of the object variable being confined to the code in the curly brackets, then you can do this:

that one isn't too far off from the typical thing we do when reading a file, like this:

or alternatively as suggested by rzwitserloot:

that way it polls only once, and omitting a break in the body of the loop does no harm. Nulling out the object in the increment makes sure the loop terminates after the first pass.

It is kind of abusive having a for loop where you have no intention of looping. I would stay with the multi-line version you started with.

But if you are polling, usually you need a loop anyway.

Nathan Hughes's user avatar

  • How about: for (Object object = queue.poll(); object != null; object = null) { /* do whatever (no break needed) */ } ? Still dubious, but shorter and cleaner than abusing Optional, and it saves a line, I guess, vs your implementation. –  rzwitserloot Commented Apr 19, 2022 at 17:58
  • 1 I like the ingenuity, but I see this potentially causing confusion if people don't see the break, but definitely would like the first one as an alternative to a poll in a while loop that has a declaration above it. Thanks –  reveance Commented Apr 19, 2022 at 18:13

May not too nice looking:

So you might have a better opinion of the straight:

Joop Eggen's user avatar

  • 1 this is what the OP asked for, didn't say it couldn't be ugly.,.. –  Nathan Hughes Commented Apr 19, 2022 at 17:58
  • 1 it is abusing Optional. mine is abusing for. not sure which is worse. :-| –  Nathan Hughes Commented Apr 19, 2022 at 18:05
  • My answer was triggered by the null safe Optional. However it still is a two-liner when the expression is placed on two lines. "Ugly" is relative here as Deque does only provide a nullable poll() . So Nathan is right w.r.t. to that. –  Joop Eggen Commented Apr 19, 2022 at 18:06
  • Let's wait for an answer with try (new AutoCloseable ...) { - ;). –  Joop Eggen Commented Apr 19, 2022 at 18:08
  • 1 I like this one the most personally, even though it's not beautiful, it does do exactly what I want with the least amount of (needless imo) instructions from me –  reveance Commented Apr 19, 2022 at 18:17

The condition is slightly contrived. Therefore, it's hard to meet the requirement without misusing something, like hiding a null -check with optional , which isn't intended for that purpose.

Actually, the following code will be both the most simple and expressive:

Elimination of a single line will have a cost - the readability of code.

The approach I came up with is to use Stream.ofNullable() which will produce an empty stream if the provided argument is null . Then turn the stream into an iterator and invoke forEachRemaining() on it. This method expects a Supplier , and you can define it on the spot by placing the logic from the if -statement, or separately.

Note : forEach() method defined by the Stream interface isn't used here deliberately in order to be aligned with the guidelines of the Stream API documentation in regard to side-effects . And an Iterator is being used instead because there's no such requirements for its method forEachRemaining() .

Turn your poll() into a supplier and pretend you're working in a language that encourages monkey patching

Kayaman's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java if-statement null nullable or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Should we burninate the [lib] tag?
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • How does one determine if something is "Modern" or not?
  • A chess engine in Java: generating white pawn moves
  • How will the ISS be decommissioned?
  • Why is there no catalog of black hole candidate?
  • Would a spaceport on Ceres make sense?
  • Tombs of Ancients
  • What is the relationship between gravitation, centripetal and centrifugal force on the Earth?
  • Why can Ethernet NICs bridge to VirtualBox and most Wi-Fi NICs don't?
  • Huygens' principle and the laws of reflection/refraction
  • Could space habitats have large transparent roofs?
  • Simple Container Class
  • An alternative way to solve a classic problem of combinatorics
  • Can a directed set be empty?
  • How to patch command to work differently in math mode?
  • DSP Puzzle: Advanced Signal Forensics
  • Trying to determine what this item is
  • Co-authors with little contribution
  • Should I accept an offer of being a teacher assistant without pay?
  • How can these passive RLC circuits change a sinusoid's frequency?
  • Are both vocal cord and vocal chord correct?
  • QGIS Labeling expression to format a values list in a series of 2 columns of 2 records
  • Are positions with different physical pieces on two squares but same kind and same color, considered the same?
  • How to make D&D easier for kids?
  • Different Bekenstein bound equations – what’s the difference?

java null check and assignment

java null check and assignment

Improving OpenJDK Scalar Replacement – Part 2/3

java null check and assignment

Cesar Soares

June 26th, 2024 0 2

In the previous part of this blog series , we explored the foundational concepts and purpose of scalar replacement (SR) in OpenJDK, laying the groundwork for understanding how this optimization can boost the performance of Java applications. Now, in the second installment of the series, we shift our focus to the specific enhancements that we have introduced to the SR implementation, highlighting how it lifts the constraints identified in the original SR implementation in the C2 compiler.

The Improvement 

Listing 1 shows a version of the CompositeChecksum method that’s slightly different from the previous one. In this version, there is a check to see if the message that we obtained from the list is null or not. If it is null, it creates a message object with the Clear string as payload; otherwise, it just creates the message object using the msg payload. This is quite a simple piece of code and a somewhat common pattern to write, however before our work to improve C2 scalar replacement, C2 would not scalar replace the Message objects in cases like this.   

Image listing1

  Listing 1: The CompositeChecksum control flow merge version.  

To understand why this is a more complicated scenario for scalar replacing the objects, let us see how C2 represents the method shown in Listing 2 , which is basically the first line of the loop in Listing 1. In the method two Message objects are allocated in different branches of an “ if ” but only a single field of one of the objects is later used.  

Image listing2

Listing 2: A simple method with an allocation merge.  

From C2’s “perspective” there is more than one place (allocation site) where the object that m will eventually reference may be allocated. To be more precise, the variable m will reference the object allocated in the then block or the object allocated in the else block of the conditional. Note that this is a simple example where there are only two allocation sites; in practice, there may be many places where an object is assigned to the same reference. There are other cases where you would expect C2 to scalar replace objects, but it does not do so. However, the allocation merge issue was the most prominent at the time that we started our investigation. See this article where we discuss those cases: HotSpot Escape Analysis and Scalar Replacement Status .  

A detailed explanation of why C2 was not scalar replacing objects in such a code pattern is a topic for a more technical compiler-related blog post. However, just to give an idea why this is a complicated piece of code to optimize, consider these points:     

  • There may be more than two allocation sites in the allocation merge.  
  • Some of the allocation sites may be an object being returned by another method.   
  • The allocation merge may be of Arrays, not of single dimensional (scalar) objects.  
  • An allocation site can simply be a null expression.  
  • Objects can also be used, including changed, by other methods before they are assigned to m .   
  • In more extreme cases the object may be stored in global variables and accessed by other threads before the assignment to m .  
  • During scalar replacement, the compiler must track the values of each field of each potential object. There may be many fields and some of these fields are other objects.  
  • The objects may be created from different classes.  
  • C2 will need to handle objects used in deoptimization points.  

Another complicating factor is the approach used by C2 to represent the code of the method while compiling it. C2 uses a concept called sea-of-nodes to represent methods internally. That representation has a property called Static Single-Assignment (SSA) which basically means that every piece of data (variable, object, etc.) can only be created in one specific point in the method. One way of making sure that this property is maintained is by labelling every piece of data in the method with a version number. You can imagine a version as roughly the line number of where the data is created. If the data (variable, object, etc.) can be created in more than one place it will have different versions . At some points in the method, it will be necessary to “merge” the versions of the variables and to do that a thing called a Phi function or Phi node is used. When the compiler is parsing a method, and it notes that a variable can point to more than one version of data, it will insert a Phi node that will represent all data versions that the variable can point to.  

Figure 1 shows a partial illustration of how C2 will represent the method shown in Listing 2. In this illustration rectangles and squares represent instructions in the compiler internal representation, while arrows connecting these instructions means that the target of the arrow uses data created by the source of the arrow. The two Allocate nodes represent instructions used to allocate memory regions for each of the two allocation sites in the method. The CheckCastPP nodes represent instructions to cast the pointers to the allocated memory regions to pointers to actual Message objects. Note that this is how the compiler represents the method, it does not mean that both object allocations will always happen – it only means that they can happen.  

In our illustration C2 inserted the Phi node to represent the fact that the variable m can point to an object allocated in one of two different allocation sites. This Phi node is what we were referring to earlier as Allocation Merge. The Phi node itself is also versioned and so the instructions after it, in this case, refer to a single version. Just for completeness, the AddP instruction computes the address of a field of an object, the Load instruction fetches data from that field, and the Return instruction represents returning some data to the caller of the method.     

Image Untitled 1

Figure 1: How C2 internally represents part of the whichPayload method.  

Scalar replacement, however, needs to know exactly which object is being used at every point where it needs to patch the code. If there is ambiguity, or a Phi node is present, that involves the object that we want to scalar replace then we need to use a more complex algorithm to decide which object it should use and moreover to patch the code of the method .  

We tried different approaches but, in the end, it turns out that the most obvious solution was the easiest one to implement and the one that performed better in the benchmarks. The idea is very simple: instead of using the conditional to only decide which object we should load the field from, we replicate the field load itself inside the branches of the conditional so that every branch has a field load and then the Phi node is used to represent that we can use either of the field loads, not either of the objects.   

Image Figure2

Figure 2: How we solved the allocation merge problem.  

Figure 2 shows an illustration of what I am referring to and Listing 3 shows the Java version of it. Note that there are 2 field loads, one for each object, and the Phi node now uses the values loaded from each of the objects. So now what we are doing is using the Phi node to decide which of the loaded values we should return, not which of the objects we should load the field from. After that transformation, the earlier scalar replacement logic in C2 can scalar replace both objects represented at the top because the objects themselves are not used by Phi nodes. Listing 4 shows the code after scalar replacement and after other optimizations kick in to just simplify the code.  

Image carbon 3

  Listing 3: Merging field loads instead of objects.  

Image listing4

As I mentioned earlier, the idea was simple. However, as expected the implementation was the most difficult part. I showed just the overall idea that we used to solve the problem and the simplest cases where objects are used only to load a single field. In practice there are many more different use cases that we need to handle. The most obvious one is when you are loading several fields from the objects or storing values on these fields, as well as a mix of these operations. Other use cases, like the objects being used as a Monitor, also must be considered. Not only was the way that the objects are being used a challenge but getting the representation of the method updated correctly was particularly challenging. In practice these representations can have thousands of nodes. It is also necessary to cooperate with other optimizations that change the representation before and after scalar replacement.   

Two other big challenges were the handling of the optimizations, like what happens when compiled code is executing and something happens that needs to cause the execution of the method to go to the interpreter. That was something that needed a lot of work and we had to do it before everything else that we worked on. The other major challenge was updating and/or traversing the memory graph. By that I mean which value I should use when I scalar replace an object in the example that I showed earlier – the field loads and the use of the data were very close, but in a bigger method these things can be very far apart so you need to traverse the graph and find the right node that has the correct value that you should use for the field. Of course, we should not break any of the existing code, especially not the existing scalar replacement code.  

How to Give it a Try  

These improvements are enabled by default in OpenJDK Tip and Microsoft Build of OpenJDK versions 11, 17 and 21. To use them, download our JDK and launch your application as you normally would! If you want to disable the optimization, let’s say for benchmarking purposes, or because you found an issue, you can do so by adding these options to the JVM launch configuration: -XX:+UnlockDiagnosticVMOptions –XX:-ReduceAllocationMerges .  

In summary, by transforming object allocation merges into merges of object fields, we make it possible for the C2 compiler to scalar replace the objects and also perform additional optimizations to the code. These enhancements make applications run smoother and faster, using resources more effectively. In the final part of this series, we’ll share the results of our work and how these changes positively impact application performance.

java null check and assignment

Leave a comment Cancel reply

Log in to start the discussion.

light-theme-icon

Insert/edit link

Enter the destination URL

Or link to existing content

Initialize an ArrayList with Zeroes or Null in Java

Last updated: January 8, 2024

java null check and assignment

  • Java Collections

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

A quick guide to materially improve your tests with Junit 5:

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> REST With Spring (new)

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Get started with Spring Boot and with core Spring, through the Learn Spring course:

1. Overview

In this tutorial, we’ll explore different ways to initialize a Java ArrayList with all values null or zero. We can also play with the initializations as we like and initialize the lists with different numerical values ​​or objects.

2. Using for Loop

When thinking about the problem of initializing the ArrayList with a desired value or object, the first solution that comes to our mind is using a simple for loop. And rightfully so, this is a straightforward and viable solution:

We declare an empty ArrayList and use the add() method for a loop.

3. Using the ArrayList Constructor Method

Another method, maybe not so well-known, would be to use one of the constructors of the ArrayList class. This takes as an argument a collection and constructs a new ArrayList containing the elements of the specified list in the order the collection’s iterator returns them. To provide the desired list to our constructor, we’ll use the nCopies() function of the Collections class . This function takes as arguments the item and the number of copies needed. We can also write a unit test to check that our constructor works appropriately:

We’ll check if the list has the desired number of elements and if all are equal to our demanded value. There are multiple ways to check if the elements of a list are all the same . For our example, we use the allMatch() function of the Java Stream API .

4. Using Java Stream API

In the previous example, we used the Java Stream API to determine if we initialized the list correctly. But, the Java Stream is capable of much more. We can use the static function generate() to produce an infinite amount of elements based on a supplier:

The limit() function takes as an argument a number. This represents the number of elements the stream should be limited to, and the method returns a new Stream consisting of objects picked from the original stream.

5. Using IntStream

We can initialize the list with a desired numeric value using the IntStream class. This is a class derived from the BaseStream , like the Stream interface. This implies that this class is capable of most things that the Stream class is capable of. This class let us create a stream of primitive numbers. Then we use the boxed() function to wrap the primitives to objects. After that, we can easily collect all the numbers generated:

We should also consider that this method works only to insert primitive numbers. So, we can’t use this method to initialize the list with null values.

6. Using Arrays.asList

The asList() is a method of java.util.Arrays class. Using this method, we can convert an array to a collection. So, for this method, we should initialize an array. Because our array contains only null values at the initialization, we use the method fill() to populate it with our desired value, 0, in our case. This method works like nCopies() , populating our array with the value given as a parameter. After filling the array with zeros, we can finally convert it to a list using the toList() function:

In this example, we should consider that we got a List as a result and not an ArrayList . And if we try to add a new element to the list, we’ll get an UnsupportedOperationException . This problem can be solved easily using the method presented in the previous section. We need to convert the List into an ArrayList . And we can do this by changing the  integerList declaration into:

Also, we can make this method add null values to our list just by removing the fill() method call. As said before, arrays are initialized with null values by default.

7. Using Vector Class

Like the ArrayList class, the Java Vector class represents a growable array of objects. In addition, Vector is a Java legacy class that implements the List interface. So we can easily cast it to a list. However, despite all the similarities between the two entities, they’re different and have different use cases. A rather significant difference is that the Vector class has all methods synchronized.

The advantage of the Vector in our problem is that it can be initialized with any number of elements. Besides this, all its elements will be null by default:

We use the function setSize() to initialize the Vector with the desired number of elements. After that, the Vector will fill itself with null values. We must consider that this method only helps us if we want to insert null values ​​in our list.

We can also transform the list to an ArrayList by using the constructor of the ArrayList class like in the previous examples or by using the method addAll() to add all elements in our newly initialized empty ArrayList .

8. Conclusion

In this quick tutorial, we’ve explored all the alternatives when we need to initialize an ArrayList with null or 0 values. In particular, we went through examples using streams, arrays, vectors, or sample loops.

As usual, you can find all the code samples over on GitHub .

Just published a new writeup on how to run a standard Java/Boot application as a Docker container, using the Liberica JDK on top of Alpaquita Linux:

>> Spring Boot Application on Liberica Runtime Container.

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Build your API with SPRING - book cover

IMAGES

  1. How to Check Null in Java (with Pictures)

    java null check and assignment

  2. What does null mean in Java

    java null check and assignment

  3. Null

    java null check and assignment

  4. How to Check Null in Java (with Pictures)

    java null check and assignment

  5. What is Java Null?

    java null check and assignment

  6. Java

    java null check and assignment

VIDEO

  1. Null checking in JAVA #shorts #javaprogramming #java

  2. Why and how to avoid null checks (part 1)

  3. JavaScript interview question. Difference between null and undefined #javascriptinterview #shorts

  4. Java null pointer exception problem full solution in image compression. merge dsd file in very easy

  5. Java for Testers

  6. Java для начинающих

COMMENTS

  1. Shortest way to check for null and assign another value if not

    Try this: this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty : planRec.approved_by.toString(); You can also use the null-coalescing operator as other have said - since no one has given an example that works with your code here is one:

  2. Best way to check for null values in Java?

    5. Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code. Method 3 is just wrong on every level. You know the item may be null so it's not an exceptional situation it's something you should check for. Method 2 is just making it more complicated than it needs to be.

  3. Avoid Check for Null Statement in Java

    This causes a NullPointerException at line 6. So, accessing any field, method, or index of a null object causes a NullPointerException, as can be seen from the examples above. A common way of avoiding the NullPointerException is to check for null: public void doSomething() {. String result = doSomethingElse();

  4. Checking for Nulls in Java? Minimize Using "If Else"

    Returns an Optional describing the given value, if non-null, otherwise returns an empty Optional.¹. The returned value from this method will never be null. If it is null, the returned value will be Optional.empty(). This way, if the result of this method is used somewhere else, there will be no chance of getting a NPE.

  5. What Is the null Type in Java?

    null is a special type that has only one possible value. In other words, the set of possible values has only one element. This characteristic alone makes the null type very peculiar. Normally, the whole purpose of variables is that they can assume different values. There's only one null reference, so a variable of the null type could only ...

  6. Check If All the Variables of an Object Are Null

    Another option is to use the utility class ObjectUtils from the Apache commons-lang3 library. The ObjectUtils's allNull() method has a generic API that handles any type and number of parameters. That method receives an array of Objects and returns true if all values in that array are null.. Otherwise, return false.Let's first add the latest version of the commons-lang3 dependency to our ...

  7. How to Check null in Java

    In order to check a null string, we have some predefined methods of string. Let's take some examples of different data types to understand how we can check whether they are null or not. String. In Java, String can be null, empty, or blank, and each one of them is distinct. 1. An empty string is a string object having some value, but its length ...

  8. Better Null-Checking in Java

    Examples like these have led a lot of the Java community to declare that Optional.get is a Code Smell.. A Better Way Other languages like Groovy and C# have a nice null-conditional operator that allows the programmer to specify that a chain of references might contain a null somewhere along the way, and a natural way to deal with that is to just short-circuit the chain of calls and result in a ...

  9. Java 8 Optional: Handling Nulls Properly

    Java 8 introduced the Optional class to make handling of nulls less error-prone. For example, the following program to pick the lucky name has a null check as: 12. 1. public static final List ...

  10. Java 8 Object Null Check

    Another way to check for null values in Java 8 is to use the Objects.requireNonNull () method. This method throws a NullPointerException if the passed reference is null. Here's an example: Objects.requireNonNull (myObject, "myObject must not be null"); // handle non-null case. Objects.requireNonNull (myObject, "myObject must not be null ...

  11. Java Assignment Operators with Examples

    Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.

  12. Java Ternary Operator

    As you can see, both of these code examples avoid calling object.getValue() if the object reference is null, but the first code example is a bit shorter and more elegant. Ternary Operator as Type Check. It is also possible to use the Java ternary operator as a type check. Here is an example of using the Java ternary operator as a type check:

  13. Null-Checking Done Right with Optionals

    Fortunately, you can reduce your null-checking boilerplate code using the Optional class for most of the cases. The Optional API was first introduced as part of the Java Development Kit 8, and ...

  14. Check if an Integer Value Is Null or Zero in Java

    So, next, let's see them in action. 2. Using the Standard Way. Using the logical OR operator could be the first idea to perform the check. It simply checks if the given Integer number is null or zero. Let's create a method to implement this check for easier verification: return num == null || num == 0 ;

  15. Java: How to assign to a variable if the result is null?

    1. Use a temp variable to only call HtmlUtil.escape once. Then check for null and assign to address1: String tempAddress = HtmlUtil.escape(rs.getString("address1"));

  16. Nullish coalescing assignment (??=)

    No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

  17. Difference Between == and equals() in Java

    Therefore, we must remember to first check that the value on which we are calling the equals() method is not null, otherwise, it can lead to annoying bugs. Moreover, since Java 7, we can use a null-safe Objects#equals() static method to perform equality checks: assertFalse(Objects.equals(e, a)); assertTrue(Objects.equals(null, e));

  18. Concise Java Code: assignment, null check and conditional execution

    Concise Java Code: assignment, null check and conditional execution. Ask Question Asked 7 years, 6 months ago. Modified 7 years, 6 months ago. Viewed 169 times 1 The following Java code appears to be fairly lengthy and somewhat repetitive. ... Java - variable Declaration, Assignment and null-check in a single statement. Hot Network Questions

  19. Expressions and operators

    An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = f() is an assignment expression that assigns the value of f() to x. There are also compound assignment operators that are shorthand for the operations listed in the ...

  20. Java

    for (Object object = queue.poll; object != null; object = null) { // do something with object } that way it polls only once, and omitting a break in the body of the loop does no harm. Nulling out the object in the increment makes sure the loop terminates after the first pass.

  21. Improving OpenJDK Scalar Replacement

    In the previous part of this blog series, we explored the foundational concepts and purpose of scalar replacement (SR) in OpenJDK, laying the groundwork for understanding how this optimization can boost the performance of Java applications.Now, in the second installment of the series, we shift our focus to the specific enhancements that we have introduced to the SR implementation, highlighting ...

  22. Convert Null Value to a Default Value in Java

    To get a default value if the provided is null, we can use MoreObjects: String actual = MoreObjects.firstNonNull(givenValue, defaultValue); assertDefaultConversion(givenValue, defaultValue, actual); MoreObjects replaces the Guava's Objects utility class, which was deprecated and planned for removal.

  23. Initialize an ArrayList with Zeroes or Null in Java

    2. Using for Loop. When thinking about the problem of initializing the ArrayList with a desired value or object, the first solution that comes to our mind is using a simple for loop. And rightfully so, this is a straightforward and viable solution: ArrayList<Integer> arrayList = new ArrayList <>(); for ( int i = 0; i< 10; i++) {.