Java provides four logical operators, which operate on
boolean operands only, in descending order of precedences, as follows:
Operator
|
Description
|
Usage
|
!
|
Logical NOT
|
!booleanExpr
|
&&
|
Logical AND
|
booleanExpr1 && booleanExpr2
|
||
|
Logical OR
|
booleanExpr1 || booleanExpr2
|
Truth table of logical operator
A
|
B
|
A||B
|
A&&B
|
!A
|
False
|
False
|
False
|
False
|
True
|
False
|
True
|
True
|
False
|
True
|
True
|
False
|
True
|
False
|
False
|
True
|
True
|
True
|
True
|
False
|
Example:
// Return true if x is between 0 and 100 (inclusive)
(x >= 0) && (x <= 100)
// wrong to use 0 <= x <= 100
// Return true if x is outside 0 and 100 (inclusive)
(x < 0) || (x > 100)
//or
!((x >= 0) && (x <= 100))
// Return true if year is a leap year
// A year is a leap year if it is divisible by 4 but not by
100, or it is divisible by 400.
((year % 4 == 0) && (year % 100 != 0)) || (year %
400 == 0)
Exercise: Study the following program, and explain its
output.
/*
* Test relational and
logical operators
*/
public class RelationalLogicalOpTest
{
public static void main(String[] args) {
int age = 18;
double weight = 71.23;
int height = 191;
boolean married = false;
boolean attached = false;
char gender = 'm';
System.out.println(!married &&
!attached && (gender == 'm'));
System.out.println(married &&
(gender == 'f'));
System.out.println((height >= 180)
&& (weight >= 65) && (weight <= 80));
System.out.println((height >= 180) ||
(weight >= 90));
}
}
No comments:
Post a Comment
Please write your view and suggestion....