Assigning Long Long in Java

I am currently browsing 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 long (primitive). Now I have not written Java for a while, but only in C #, but how can a Long longVariable variable object ever be null?

+4
source share
4 answers

If getLong() really has a return type of long , it cannot be, i.e. l will never be null. The programmer probably did not look at the return type, but was inferred from the method name a long .

+6
source

What if you pass the wrong identifier? Then it is not found, but you get zero, or is an exception raised? The 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 

Therefore, it never returns null, but ultimately 0L. However, getLongArray sometimes returns null, so can it be left away from using getLongArray?

+2
source

Java Long has an object, and like any object, it can be null. Long is a primitive type and cannot be null.

From Java 1.5 to Wards, Java supports automatic boxing and unpacking, meaning that it automatically converts between primitives and objects.

If a method returns Long , then it probably will not check for null , even if you add it to Long , however, if the method returns a Long object, it is a good idea to check for zeros.

+1
source

Try creating a new instance. bundle.getLong(someId) returns the primitive type long not long . Long l = new Long(bundle.getLong(someId));

And then check if(l != null)

Make sure you select the correct long from the Bundle . Try Log ging this long object if everything is ok.

Log.i("MY LONG: ", String.valueOf(l));

0
source

All Articles