Java: Booleans

What are Booleans?

Booleans are variables that always equal a value of true or false.

For example, the piece of code below is a boolean.

boolean example = true;

example is the name, and it equals true.

 

Another way to write a boolean is below

boolean math = 3 > 4;

The boolean math is false, because 3 is not greater than four.

 

Boolean operators

Boolean operators compare and identify two statements as true or false.

There are different boolean operators.

  • And (&&) boolean operator
    • The And boolean operator is represented by &&
    • If both sides of the And boolean operator are true, the boolean is true
    • boolean math = 4 > 5 && 10 < 11 ; //false, because both sides of the operator have to be true
    • boolean mathTime = 5 == 3 + 2 && 10 > 1 ; //true, because both sides of the operator are true
  • Or (||) boolean operator
    • The Or boolean operator is represented by ||
    • If at least one side of the  Or boolean operator is true, the boolean is true
    • boolean mathExample = 3 < 4 || 4 == 2 ; //true, because at least one side of the operator  is true
  • Not (!) boolean operator
    • The Not boolean operator is represented by !
    • If the statement is true, the Not operator makes it false
    • If the statement is false, the Not operator makes it true
    • boolean opposite = !(3 > 4); //True, because the statement is false, and the Not operator makes it true

 

You can print booleans by copying the code below.

System.out.println( !(4 + 5 = 9) &&  3 > 4 || 1 < 3);

The first part is true, and the Not operator makes it false. The second part  say 3 > 4(false) or 1 < 3(True).

The first part is false, and the second part is true. The And operator is in the middle, which means since only one side is true, False gets printed on the screen.

 

 

 

Leave a comment