I found this code in a book and I executed it in Netbeans:
boolean b = false;
if(b = true) {
System.out.println("true");
} else {
System.out.println("false");
}
I just don't understand why the output of this code is true, Can anyone enlighten me please, Thanks.
Definition: A Boolean is a type of data that has only two possible values: true or false. You can think of a boolean like the answer to a yes or no question. If the answer is yes, the Boolean value is true. If the answer is no, the boolean value is false.
A bool expresses a truth value. It can be either true or false .
The literal of a boolean value is True or False . The Tableau INT() function converts a boolean to a number, returning 1 for True and 0 for False.
There are just two values of type bool: true and false. They are used as the values of expressions that have yes-or-no answers. The following table shows some operators that yield boolean results and some operations on boolean values. True if x and y are the same value.
It's missing the double-equals. So it's doing an assignment instead of an equality comparison (and remember, the return value of an assignment is the new value). In most cases, the fact that most types are not boolean means the result is not a boolean and so it becomes illegal for an if
statement, resulting in a compiler error. However, since the type here is already a boolean, the assignment results in a boolean and so the safety-check fails. Thus, b = true
means that b
is assigned the value true
and this is the value that is returned and checked by the if
statement.
This is because the if-statement condition isn't a comparison. It's an assignment:
if(b = true)
Which will always return true. So it will always print true
.
If you wanted to do a comparison, you need to use ==
.
In your "if" statement you are assigning the value "true" to b. You should check the value by using the comparison operator "==".
boolean b = false;
if(b == true)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
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