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
0really mean the same thing in your program). I realize that’s not much of an answer, but it’s the truth. 🙂 If “unset” and0didn’t mean the same thing, that would argue more strongly forIntegerso you could properly differentiate them.Re your comment below:
Yes,
intis always initialized to0, per Section 4.12.5 of the JLS.