Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Checking if an attribute is set with int and Integer

Tags:

java

types

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?

like image 639
Daniel Scocco Avatar asked Jan 30 '26 18:01

Daniel Scocco


1 Answers

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.

like image 128
T.J. Crowder Avatar answered Feb 01 '26 06:02

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!