Java Reference
In-Depth Information
If the
boolean-expression
evaluates to
true
, the statements in the block are executed.
As an example, see the following code:
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) is
wrong. It should be corrected, as shown in (b).
if
i >
0
{
System.out.println(
"i is positive"
);
}
if
(i >
0
) {
System.out.println(
"i is positive"
);
}
(a) Wrong
(b) Correct
The block braces can be omitted if they enclose a single statement. For example, the fol-
lowing statements are equivalent.
if
(i >
0
){
System.out.println(
"i is positive"
);
}
if
(i >
0
)
System.out.println(
"i is positive"
);
Equivalent
(a)
(b)
Note
Omitting braces makes the code shorter, but it is prone to errors. It is a common mistake
to forget the braces when you go back to modify the code that omits the braces.
Omitting braces or not
Listing 3.2 gives a program that prompts the user to enter an integer. If the number is a
multiple of
5
, the program displays
HiFive
. If the number is divisible by
2
, it displays
HiEven
.
L
ISTING
3.2
SimpleIfDemo.java
1
import
java.util.Scanner;
2
3
public class
SimpleIfDemo {
4
public static void
main(String[] args) {
5 Scanner input =
new
Scanner(System.in);
6 System.out.println(
"Enter an integer: "
);
7
int
number = input.nextInt();
enter input
8
9
if
(number %
5
==
0
)
10 System.out.println(
"HiFive"
);
11
12
if
(number %
2
==
0
)
13 System.out.println(
"HiEven"
);
14 }
15 }
check 5
check even
Search WWH ::
Custom Search