Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

False boolean = True?

Tags:

java

boolean

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.

like image 757
Marwen Hizaoui Avatar asked Oct 25 '11 00:10

Marwen Hizaoui


People also ask

What is a false Boolean?

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.

Is Boolean always true or false?

A bool expresses a truth value. It can be either true or false .

Is Boolean true or false or 1 or 0?

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.

What makes a Boolean true?

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.


3 Answers

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.

like image 78
Kirk Woll Avatar answered Oct 01 '22 04:10

Kirk Woll


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 ==.

like image 40
Mysticial Avatar answered Oct 01 '22 06:10

Mysticial


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");
}
like image 35
George Avatar answered Oct 01 '22 04:10

George