Java Reference
In-Depth Information
3.1
List six comparison operators.
✓
✓
Check
3.2
Show the printout of the following statements:
Point
System.out.println(
'a'
<
'b'
);
System.out.println(
'a'
<=
'A'
);
System.out.println(
'a'
>
'b'
);
System.out.println(
'a'
>=
'A'
);
System.out.println(
'a'
==
'a'
);
System.out.println(
'a'
!=
'b'
);
3.3
Can the following conversions involving casting be allowed? If so, find the converted
result.
boolean
b =
true
;
i = (
int
)b;
int
i =
1
;
boolean
b = (
boolean
)i;
An
if
statement executes the statements if the condition is true.
Key
Point
The preceding program displays a message such as “
6
+
2
=
7
is false.” If you wish the
message to be “
6
+
2
=
7
is incorrect,” you have to use a selection statement to make this
minor change.
Java has several types of selection statements: one-way
if
statements, two-way
if-else
statements, nested
if
statements,
switch
statements, and conditional expressions.
A one-way
if
statement executes an action if and only if the condition is
true
. The syntax
for a one-way
if
statement is:
why
if
statement?
if
statement
if
(boolean-expression) {
statement(s);
}
The flowchart in Figure 3.1 illustrates how Java executes the syntax of an
if
statement.
A
flowchart
is a diagram that describes an algorithm or process, showing the steps as boxes
of various kinds, and their order by connecting these with arrows. Process operations are
represented in these boxes, and arrows connecting them represent the flow of control. A
diamond box is used to denote a Boolean condition and a rectangle box is for representing
statements.
If the
boolean-expression
evaluates to
true
, the statements in the block are executed.
As an example, see the following code:
flowchart
if
(radius >=
0
) {
area = radius * radius * PI;
System.out.println(
"The area for the circle of radius "
+
radius +
" is "
+ area);
}
The flowchart of the preceding statement is shown in Figure 3.1b. If the value of
radius
is greater than or equal to
0
, then the
area
is computed and the result is displayed; otherwise,
the two statements in the block will not be executed.
The
boolean-expression
is enclosed in parentheses. For example, the code in (a)
below is wrong. It should be corrected, as shown in (b).