Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning long to Long in Java

I am currently going through one of the Android Tutorials. I found an expression like:

Bundle bundle = getIntent().getExtras();
Long longVariable = bundle.getLong(someId);
if( longVariable != null )
{
  //doSomething
}

After looking at Bundle.getLong in the API I saw that it returns a long (primitive). Now, I didn't write Java for quite a while, only C# in the meanwhile, but how can the object Long longVariable variable ever be null?

like image 516
StampedeXV Avatar asked Jan 18 '23 23:01

StampedeXV


2 Answers

If getLong() really has return type long it can't be, i.e. l will never be null. Probably the programmer didn't look up the return type, but inferred from the method name a Long would be returned.

like image 103
meriton Avatar answered Jan 28 '23 19:01

meriton


What if you pass in the wrong id? Then it is not found, but do you get null, or an exception is raised? Documentation states that:

public long getLong (String key)
Returns the value associated with the given key, 
or 0L if no mapping of the desired type exists for the given key.  
Parameters

     key    a String
Returns
     a long value

So it never returns null, but 0L eventually. However, getLongArray returns null sometimes, so it might be a leftover from using getLongArray?

like image 26
Kheldar Avatar answered Jan 28 '23 19:01

Kheldar