I'm learning Java, coming from C and I found an interesting difference between languages with the boolean
type. In C there is no bool
/ean
so we need to use numeric types to represent boolean logic (0 == false
).
I guess in Java that doesn't work:
int i = 1; if (i) System.out.println("i is true");
Nor does changing the conditional via a typecast:
if ((boolean)i)
So besides doing something like:
if ( i != 0 )
Is there any other way to do a C-ish logic check on an int
type? Just wondering if there were any Java tricks that allow boolean logic on non-boolean types like this.
EDIT:
The example above was very simplistic and yields itself to a narrow scope of thinking. When I asked the question originally I was thinking about non-boolean returns from function calls as well. For example the Linux fork()
call. It doesn't return an int
per se, but I could use the numeric return value for a conditional nicely as in:
if( fork() ) { // do child code
This allows me to process the code in the conditional for the child, while not doing so for the parent (or in case of negative return result for an error).
So I don't know enough Java to give a good "Java" example at the moment, but that was my original intent.
To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!
The compare() method of Java Boolean class compares the two Boolean values (x and y) and returns an integer value based on the result of this method.
To convert integer to boolean, firstly let us initialize an integer. int val = 100; Now we will declare a variable with primitive boolean. While declaration, we will initialize it with the val value comparing it with an integer using the == operator.
Boolean values still behave as integers, can be stored in integer variables, and used anywhere integers would be valid, including in indexing, arithmetic, parsing, and formatting.
In Java,
if ( i != 0 )
is the idiomatic way to check whether the integer i
differs from zero
.
If i
is used as a flag, it should be of type boolean
and not of type int
.
Why not use the boolean
type ? That will work as you expect without the potentially problematic integer/boolean conflation.
private boolean isValid; ... if (!isValid) { ... }
Note that this is the idiomatic Java approach. 3rd party libs use this, and consumers of your API will use and expect it too. I would expect libs that you use to give you booleans
, and as such it's just you treating ints
as booleans
.
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