Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to define true, false, unset state

Tags:

java

boolean

If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.

What's the best practice to achieve this? Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?

like image 224
Tom Martin Avatar asked Nov 24 '08 17:11

Tom Martin


People also ask

How do you change a boolean from false to true?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

How do you set a boolean to true?

boolean user = true; So instead of typing int or double or string, you just type boolean (with a lower case "b"). After the name of you variable, you can assign a value of either true or false.

What does true/false mean in Java?

A boolean variable in Java can be created using the boolean keyword. Unlike C++, a numerical value cannot be assigned to a boolean variable in Java – only true or false can be used. The strings “true” or “false” are​ displayed on the console when a boolean variable is printed.

What is a false boolean?

false is a primitive and Boolean. FALSE is an object, so they're not really comparable. If you assign false to a Boolean variable, like this: Boolean b = false; Java's auto boxing occurs to convert the primitive into an object, so the false value is lost and you end up with Boolean.


1 Answers

Boolean a = true; Boolean b = false; Boolean c = null; 

I would use that. It's the most straight-forward.

Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required:

public enum ThreeState {     TRUE,     FALSE,     TRALSE }; 

There is the advantage of the first that users of your class doesn't need to care about your three-state boolean. They can still pass true and false. If you don't like the null, since it's telling rather little about its meaning here, you can still make a public static final Boolean tralse = null; in your class.

like image 180
Johannes Schaub - litb Avatar answered Oct 08 '22 17:10

Johannes Schaub - litb