58

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

Will this work?

if ( longValue == null) { return blah; }
BrownTownCoder
  • 1,312
  • 5
  • 19
  • 25

8 Answers8

113

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

There are 8 primitive types in Java:

Data Type Size Description
byte 1 byte Int8
short 2 bytes Int16
int 4 bytes Int32
long 8 bytes Int64
float 4 bytes Single
double 8 bytes Double
boolean 1 bit Boolean

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

Long longValue = null;

if(longValue == null)
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
brso05
  • 13,142
  • 2
  • 21
  • 40
17

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.

Diablo
  • 443
  • 7
  • 21
12

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.

M A
  • 71,713
  • 13
  • 134
  • 174
10

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

Arif Ulusoy
  • 244
  • 2
  • 11
3

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

Srinath
  • 31
  • 5
1

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.

tammoj
  • 908
  • 10
  • 14
0

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 @RequestParam in Spring MVC handling optional parameters

Niraj
  • 517
  • 1
  • 5
  • 14
-7

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)
Pavithra
  • 29
  • 1
  • 1
  • 14