three-value logic in Java?

M

Mohun Biswas

A relational-database boolean can have three values: true, false, and
"unknown" aka NULL. Is there a commonly accepted idiom for representing
the analogous situation in Java? There's no primitive type which seems
to fit the bill. Of course one could use an integer type and use 0 for
false, 1 for true, and -1 for null but that's not pretty. The best I can
think of is to use an exception for the third value, e.g.

class MyClass {
private boolean setting;
private boolean settingInitialized = false;

public void setSetting(boolean setting) {
this.setting = setting;
settingInitialized = true;
}

public boolean getSetting() {
if (settingInitialized == false)
throw new NullSettingException();
return setting;
}

// In case the user would prefer to avoid handling exceptions.
public boolean isSettingInitialized() {
return settingInitialized ;
}
}

Is there another, better way?

Thanks,
MB
 
P

Phillip Lord

Mohun> A relational-database boolean can have three values: true,
Mohun> false, and "unknown" aka NULL. Is there a commonly accepted
Mohun> idiom for representing the analogous situation in Java?



Boolean setting;

can equal Boolean.TRUE, Boolean.FALSE, or null.


Phil
 
M

Mohun Biswas

pete said:
I've no idea whether it's common, but a variable of type Boolean may be
set to Boolean.TRUE, Boolean.FALSE or null.

Oh. Sorry, I'd always assumed that an uninitialized boolean was set to
false. Should've RTFM-ed more.

MB
 
J

John C. Bollinger

Mohun said:
Oh. Sorry, I'd always assumed that an uninitialized boolean was set to
false. Should've RTFM-ed more.

You may still have a misconception. The suggested solution involves use
of the Boolean class, not the primitive boolean type. Primitive types
are not compatible with the null reference.


John Bollinger
(e-mail address removed)
 
R

Roedy Green

Oh. Sorry, I'd always assumed that an uninitialized boolean was set to
false. Should've RTFM-ed more.
That is true. boolean is false, Boolean is null.
 
P

pete kirkham

Mohun said:
Oh. Sorry, I'd always assumed that an uninitialized boolean was set to
false. Should've RTFM-ed more.

MB

An uninitialized boolean field is set to false; an uninitialized Boolean
field is set to null. The capital denotes the object that wraps the
primitive.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top