Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether an Integer is null or zero in Java?

Tags:

java

Is there more concise way to write:

if (myInteger != null && myInteger != 0) { ... } 

For example, for Strings you can use StringUtils.isBlank()

like image 872
Mike Avatar asked Dec 16 '16 11:12

Mike


People also ask

Can we do null check for integer in Java?

int stores the values in the memory in the form of binary by default. It means they can't be null. Primitive data type int can not be checked for a null value.

Is 0 == null in Java?

null means that a variable contains a reference to a space in memory that does not contain an object. 0 is a numeric data type with a value of 0. Nothing doesn't really exist, however I think you may be viewing this as an empty String "" which is simply a String data type that does not contain a value.

How do you check if a value is null or not in Java?

To check if a string is null or empty in Java, use the == operator. Let's say we have the following strings. String myStr1 = "Jack Sparrow"; String myStr2 = ""; Let us check both the strings now whether they are null or empty.


1 Answers

With Java 8:

if (Optional.ofNullable(myInteger).orElse(0) != 0) {   ... } 

Note that Optional may help you to completely avoid the if condition at all, depending on your use case...

like image 174
Florian Albrecht Avatar answered Oct 02 '22 09:10

Florian Albrecht