简体   繁体   中英

Assigning a null value to an int

If the following code is possible:

Integer a = null;
int b = a;

Does it mean that a function returning a possible null value for an integer is a bad practice?

Edit 1: There are several different opinions in these answers. I am not enough confident to choose one or another.

That code will give a NullPointerException when you run it. It's basically equivalent to:

Integer a = null;
int b = a.intValue();

... which makes it clearer that it will indeed fail.

You're not really assigning a null value to an int - you're trying and failing.

It's fine to use null as a value for an Integer ; indeed often Integer is used instead of int precisely as a "nullable equivalent`.

It is not possible. You will get NullPointerException

That will throw a NullPointerException.

The reason for this is that you're relying on auto-unboxing of the Integer value to an int primitive type. Java does this by internally calling .intValue() on the Object, which is null.

As to either it's a good practice or not... I would advise against doing so, unless the code is only used by you and you're extremely well behaved, making sure that you only assign the return value of such method to Integer values, not int.

If your code ends up in a lib used by others, it's not safe, and I would rather explicitly throw an Exception, well documented, and allow for defensive coding on the caller's part.

Funny thing with Java tenerary operator ?: (using 8u151 on OSX)

If you do

Integer x = map == null ? 0 : map.get ( key );

which seems fine and compact and all, then you get an npe!!! if

map.get ( key )

is a null. So I had to split that and it worked fine.

Of course you cannot assign null to an int. But returning a null in some situations makes sense. Null can mean that the value is not set. A typical example is a DB column.

The code is possible, but throws a NullPointerException at runtime, because of unboxing. Regarding

Does it mean that a function returning a possible null value for an integer is a bad practice?

yes, it is. It's useless and dangerous (as you can see) to return an Integer when a int is enough, because objects can be null, while primitives can't. Integer should be used only when needed, like in a parameterized type - List<Integer>

That would work indeed.

Integer a = null;
Integer b = a;

But I would rather use a int value out of range (-1 if your numbers are all positive) to return in case of an error.

It's a bout Java auto-boxing.

Integer a = null;
int b = a;

this code assign a to b,actually the compiler will do this:int b=a.intValue(), so this line will throw NullPointerException;

the code :

Integer a = 1;

will actually do this: Integer a = Integer.valueOf(1);

You can use javap to see the compiled virtual machine instructions。

You can write simple test:

public class Test {
    public static void main(String[] args){
        Integer a = null;
        int b = a;

        System.out.println(b);
    }
}

And the output is a NullPointerException on int b = a;

Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

From Java 8, we can use Optional:

// example: if an Integer object is null, an int value could receive 0, for example:

Integer value = getSomeInteger (...); // (0, null, or some other numeric value)
int inteiro = Optional.ofNullable(value).orElse(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM