Monday, November 1, 2010

Boolean Values And Expressions In Java

 Boolean values and expressions in java

 Java has a data type called boolean

• possible values are true or false
• can be operated on with logical or bitwise operators, but cannot be treated as a 0 or 1 mathematically
• can be specified as a parameter type or return value for a method
• a boolean value will print as true or false

The result of a conditional expression (such as a comparison operation) is a boolean value

• simple comparisons, such as greater than, equal to, etc.
• values returned from functions
• complex combinations of simpler conditions

Condition expressions are used for program control

•branching to another section of the program under specified conditions
•repeating loops of the same section of code

Comparison Operators

This chart shows the comparison operators and the types of data they can be applied to Operator Purpose (Operation Performed) Types of Data 
boolean  numeric primitives and char  objects

==  is equal to (note the two equals signs!) X X X
!=  is not equal to X X X
>  is greater than  X 
<  is less than  X 
>=  is greater than or equal to  X 
<=  is less than or equal to  X

Comparing Objects
The operators == and != test if two references point to exactly the same object in memory - they test that the numeric values of the two references are the same
The equals(Object o) method compares the contents of two objects to see if they are the same (you can override this method for your classes to perform any test you want)

Conditional Expression Examples
a = 3; b = 4;

a == b will evaluate to false
a != b will evaluate to true
a > b will evaluate to false
a < b will evaluate to true
a >= b will evaluate to false
a <= b will evaluate to true


Complex boolean Expressions

Java has operators for combining boolean values with AND and OR logic, and for negating a value (a NOT operation)

•  there are also bitwise operators for AND, OR and bitwise inversion (changing all 1 bits to 0, and vice versa)
• since a boolean is stored as one bit, the bitwise AND and OR operators will give the same logical result, but will be applied differently (see below)
• for some reason, the bitwise NOT cannot be applied to a boolean value


Logical Bitwise
&&  logical AND
&  bitwise AND
||  logical OR
|  bitwise OR
!  logical NOT
~  bitwise NOT (inversion)

No comments:

Post a Comment