This question already has an answer here:
which is the best way to set already defined int to null?
private int xy(){
int x = 5;
x = null; //-this is ERROR
return x;
}
so i choose this
private int xy(){
Integer x = 5;
x = null; //-this is OK
return (int)x;
}
Then i need something like :
if(xy() == null){
// do something
}
And my second question can i safely cast Integer to int?
Thanks for any response.
In this case, I would avoid using
null
all together.Just use
-1
as yournull
If you need
-1
to be an acceptable (not null) value, then use afloat
instead. Since all your real answers are going to be integers, make your null0.1
Or, find a value that the
x
will never be, likeInteger.MAX_VALUE
or something.Only objects can be null. Primitives (like
int
) can't.You don't need a cast, you can rely on auto-unboxing. However it may throw a NullPointerException:
Your method compiles, but will throw NullPointerException when trying to unbox the Integer...
The choice between Integer and int depends on what you are trying to achieve. Do you really need an extra state indicating "no value"? If this is a legitimate state, use Integer. Otherwise use int.
You can't.
int
is a primitive value type - there's no such concept as anull
value forint
.You can use
null
withInteger
because that's a class instead of a primitive value.It's not really clear what your method is trying to achieve, but you simply can't represent
null
as anint
.