开发者

validate long variable if null

I am having difficultie while validating a long variable if it is null. The Code which I am using is :

long late开发者_如何学C_in= latein_hours.getTime();

It will show an error that java null pointer exception. So how can I validate if it is null then make it equal to zero.

Thanks


long late_in = 0;
if(latein_hours!=null){
    late_in= latein_hours.getTime();
}

Primitive can't be null, only reference to object can hold null value


A long can’t be null: if you don't set a value, is automatically set to 0.

If you want a variable that can be null (for example if not initialized), you must use Long (look the case). Long is like a container for long that can be null.

Long latein_hours;
long late_in;
if(latein_hours!=null){
    late_in= latein_hours.getTime();
}


The long isn't null. latein_hours is. If this is intentional, then you can do:

long late_in = latein_hours == null ? 0 : latein_hours.getTime();


I'm not sure if latein_hours is null or if getTime() returns a Long which is null. Either way you just need to check for the null like this:

long late_in = 0;
if (latein_hours != null && latein_hours.getTime() != null) {
    late_in = latein_hours.getTime(); //auto unboxing
}
else {
    // was null
}

It's the second case which often trips people up when using autounboxing, you do get some null pointer exceptions in code you thought of as just doing some maths with primitives.


if(latein_hours!=null) {
    long late_in= latein_hours.getTime();
} 

You will get a null pointer exception, if you invoke anything on the null object. i.e if

latein_hours = null;
latein_hours.getTime(); // NullPointerException
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜