Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a null value to an int

Tags:

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.

like image 837
JohnJohnGa Avatar asked Dec 17 '12 12:12

JohnJohnGa


People also ask

Can we assign null to int in C?

In c, besides pointers you cannot set c objects to NULL. You cannot cast NULL to other object since it encapsulates nothing. So you might want to set your struct variables to 0 instead of NULL.

Can you initialize an int to null?

No, but int[] can be. Show activity on this post.

Can an int field be null?

So int can not be null.


1 Answers

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`.

like image 171
Jon Skeet Avatar answered Nov 11 '22 02:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!