Java Reference
In-Depth Information
If one of the operands of an
&&
operator is
false
, the expression is
false
; if one of the
operands of an
||
operator is
true
, the expression is
true
. Java uses these properties to
improve the performance of these operators. When evaluating
p1 && p2
, Java first evaluates
p1
and then, if
p1
is
true
, evaluates
p2
; if
p1
is
false
, it does not evaluate
p2
. When
evaluating
p1 || p2
, Java first evaluates
p1
and then, if
p1
is
false
, evaluates
p2
; if
p1
is
true
, it does not evaluate
p2
. In programming language terminology,
&&
and
||
are known
as the
short-circuit
or
lazy
operators. Java also provides the unconditional AND (
&
) and OR
(
|
) operators, which are covered in Supplement III.C for advanced readers.
short-circuit operator
lazy operator
3.18
✓
✓
Assuming that
x
is
1
, show the result of the following Boolean expressions.
(
true
) && (
3
>
4
)
!(x >
0
) && (x >
0
)
(x >
0
) || (x <
0
)
Check
Point
(x !=
0
) || (x ==
0
)
(x >=
0
) || (x <
0
)
(x !=
1
) == !(x ==
1
)
3.19
(a) Write a Boolean expression that evaluates to
true
if a number stored in variable
num
is between
1
and
100
. (b) Write a Boolean expression that evaluates to
true
if
a number stored in variable
num
is between
1
and
100
or the number is negative.
3.20
(a) Write a Boolean expression for
x
-
5
6
4.5. (b) Write a Boolean expression
for
x
-
5
7
4.5.
3.21
Assume that
x
and
y
are
int
type. Which of the following are legal Java expressions?
x > y >
0
x = y && y
x /= y
x or y
x and y
(x !=
0
) || (x =
0
)
3.22
Are the following two expressions the same?
a. x %
2
==
0
&& x %
3
==
0
b. x %
6
==
0
3.23
What is the value of the expression
x >= 50 && x <= 100
if
x
is
45
,
67
, or
101
?
3.24
Suppose, when you run the following program, you enter the input
2 3 6
from the
console. What is the output?
public class
Test {
public static void
main(String[] args) {
java.util.Scanner input =
new
java.util.Scanner(System.in);
double
x = input.nextDouble();
double
y = input.nextDouble();
double
z = input.nextDouble();
System.out.println(
"(x < y && y < z) is "
+ (x < y && y < z));
System.out.println(
"(x < y || y < z) is "
+ (x < y || y < z));
System.out.println(
"!(x < y) is "
+ !(x < y));
System.out.println(
"(x + y < z) is "
+ (x + y < z));
System.out.println(
"(x + y > z) is "
+ (x + y > z));
}
}
3.25
Write a Boolean expression that evaluates to
true
if
age
is greater than
13
and less
than
18
.
Search WWH ::
Custom Search