How to check a Long for null in java

JavaNullLong Integer

Java Problem Overview


How do I check a Long value for null in Java?

Will this work?

if ( longValue == null) { return blah; }

Java Solutions


Solution 1 - Java

Primitive data types cannot be null. Only Object data types can be null.

int, long, etc... can't be null.

If you use Long (wrapper class for long) then you can check for null's:

Long longValue = null;

if(longValue == null)

Solution 2 - Java

If it is Long object then You can use longValue == null or you can use Objects.isNull(longValue) method in Java 7+ projects .

Please check Objects for more info.

Solution 3 - Java

If the longValue variable is of type Long (the wrapper class, not the primitive long), then yes you can check for null values.

A primitive variable needs to be initialized to some value explicitly (e.g. to 0) so its value will never be null.

Solution 4 - Java

You can check Long object for null value with longValue == null , you can use longValue == 0L for long (primitive), because default value of long is 0L, but it's result will be true if longValue is zero too

Solution 5 - Java

Of course Primitive types cannot be null. But in Java 8 you can use Objects.isNull(longValue) to check. Ex. If(Objects.isNull(longValue))

Solution 6 - Java

As mentioned already primitives can not be set to the Object type null.

What I do in such cases is just to use -1 or Long.MIN_VALUE.

Solution 7 - Java

If it is Long you can check if it's null unless you go for long (as primitive data types cant be null while Long instance is a object)

Long num; 

if(num == null) return;

For some context, you can also prefer using Optional with it to make it somehow beautiful for some use cases. Refer https://stackoverflow.com/questions/22373696/requestparam-in-spring-mvc-handling-optional-parameters

Solution 8 - Java

As primitives(long) can't be null,It can be converted to wrapper class of that primitive type(ie.Long) and null check can be performed.

If you want to check whether long variable is null,you can convert that into Long and check,

long longValue=null;

if(Long.valueOf(longValue)==null)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrownTownCoderView Question on Stackoverflow
Solution 1 - Javabrso05View Answer on Stackoverflow
Solution 2 - JavaDiabloView Answer on Stackoverflow
Solution 3 - JavaM AView Answer on Stackoverflow
Solution 4 - JavaArif UlusoyView Answer on Stackoverflow
Solution 5 - JavaSrinathView Answer on Stackoverflow
Solution 6 - JavatammojView Answer on Stackoverflow
Solution 7 - JavaNirajView Answer on Stackoverflow
Solution 8 - JavaPavithraView Answer on Stackoverflow