4

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

long late_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

5 Answers 5

11
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

Sign up to request clarification or add additional context in comments.

Comments

9

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();
}

Comments

6

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();

Comments

2

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.

3 Comments

-1: Assuming latein_hours is a java.util.Date object, getTime() returns a primitive long not a wrapper Long
+1 - Down-voting someone for not making a dangerous assumption stinks.
I shouldn't write comments before I vote. Yes a downvote would be too harsh and yes I would have taken it back, if I ever had voted it down. (and if you don't believe me - look at my rep)
-1
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

1 Comment

you can not use != operator for Long

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.