Suppose I have an object like this:
Public Class Test{
int a;
}
At some point in my program I want to check whether attribute a is set. I know that if I used Integer instead of int as the type of the attribute I could do something like:
if(test.a!=null)
...;
But what if I keep the int there and instead and use this to check:
if(test.a!=0)
...;
One problem is that I wouldn't be able to differentiate between a zero value and an unset value, but in my program those are the same, as valid values are all different from 0. Also, using int simplifies things I need to do later on, like comparisons using == .
So would it be fine to use int here, or Integer is always preferred?
It's totally up to you, either is fine (provided "unset" and 0 really mean the same thing in your program). I realize that's not much of an answer, but it's the truth. :-) If "unset" and 0 didn't mean the same thing, that would argue more strongly for Integer so you could properly differentiate them.
Re your comment below:
I just wanted confirmation that an unset int will always be equal to
0
Yes, int is always initialized to 0, per Section 4.12.5 of the JLS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With