Week 6, Notes 1

Boolean Variables

Variables declared to be of the primitive type boolean may hold one of two values – either true or false

 

E.g.,

boolean b;    // declare a variable to hold a boolean

b = true;     // assign the boolean literal value ‘true’ to b

Logical operators

There are two binary and one unary logical operators:

b1 && b2      // true if both b1 and b2 are true, otherwise false

b1 || b2      // false if both b1 and b2 are false, otherwise true

! b1          // true if b1 is false, false if b1 is true

 

All of the possible inputs and results for these operators are shown in the following table:

Truth Table

b1

b2

 

b1 &&  b2

b1 || b2

! b1

T

T

 

T

T

F

T

F

 

F

T

F

F

T

 

F

T

T

F

F

 

F

F

T

Know this table by memory

Relational operators and boolean operands

true != false

the result of this expression is  true

(true != false) == true

the result of this expression is  true

 

The relational operators < and > cannot be applied to boolean operands.

Example

See demos/W06N01.java.

 

New operators

Operator

Meaning

sum += d;

sum = sum + d;

count++;

count = count + 1;

Associativity

String more than one of a particular operator together, e..g, a = b = c;

Associativity says which one of the operators happens first.

For assignment (=) the rightmost happens first.

For most other operators, the leftmost happens first.

Precedence

Computers do one thing at a time.

Precedence is determining which operators happen in which order during the evaluation of an expression.

 

The following table shows the precedence order of operators.  (We do not need to know the << and >> operators.)

Example

See demos/W06N02.java.