Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I manipulate Boolean values as ints in Java? [duplicate]

Tags:

java

boolean

Is a boolean primitive in java a type in its own right or can it be manipulated as an int? In other languages I have seen, boolean types can be manipulated as if false=0 and true=1 which can sometimes be quite convenient.

like image 869
user3799584 Avatar asked Aug 04 '14 00:08

user3799584


People also ask

Can boolean be converted to int in Java?

Boolean Class Object. Using the method booleanObjectMethodToInt, we can convert a boolean value to an integer the same way we did with the static method.

Can we compare a boolean to an integer in a Java program?

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.

Can we change boolean value in Java?

Field setBoolean() method in Java with Examples When you need to set the value of a field of an object as boolean then you can use this method to set value over an Object.

How do you pass a boolean value as a reference in Java?

Everything is passed by value. You're not passing an object by reference in Java, you're passing an object reference by value. Boolean b does not hold a Boolean object, it holds a reference (a pointer) to a Boolean object. Second, Boolean (like the other wrapper objects and also String ) are immutable objects.


1 Answers

Is a boolean primitive in java a type in its own right?

Yes. boolean is a primitive type in its own right

can it be manipulated as an int?

No. It can not be implicitly or explicitly cast or otherwise used as an int (Java ain't C)

If you wanted to "coerce" it to an int:

boolean b;
int i = b ? 1 : 0; // or whatever int values you care to use for true/false
like image 126
Bohemian Avatar answered Oct 14 '22 06:10

Bohemian