This question already has an answer here:
-
What is the difference between an int and an Integer in Java and C#?
26 answers
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 your null
If you need -1
to be an acceptable (not null) value, then use a float
instead. Since all your real answers are going to be integers, make your null 0.1
Or, find a value that the x
will never be, like Integer.MAX_VALUE
or something.
You can't. int
is a primitive value type - there's no such concept as a null
value for int
.
You can use null
with Integer
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 an int
.
Only objects can be null. Primitives (like int
) can't.
can i safely cast Integer to int?
You don't need a cast, you can rely on auto-unboxing. However it may throw a NullPointerException:
Integer i = 5;
int j = i; //ok
Integer k = null;
int n = k; //Exception
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.