1

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.

user2899587
  • 189
  • 2
  • 3
  • 10
  • Write a class to wrap the integer and add a boolean called “invalid“ and set it to true whenever the integer should be null. Now you can check if the integer is invalid when calling it. You could also throw an exception when getInt() gets called but “invalid“ is true. Also you could do that as a generic class to avoid doing a class for every single primitive datatype. – Impulse The Fox Aug 24 '17 at 11:34

4 Answers4

12

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.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
11

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.

IHazABone
  • 525
  • 5
  • 20
mrres1
  • 1,127
  • 6
  • 10
6

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
assylias
  • 297,541
  • 71
  • 621
  • 741
0

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.

Eyal Schneider
  • 21,096
  • 4
  • 43
  • 73