Java Reference
In-Depth Information
boolean-
expression
false
false
(radius >= 0)
true
true
area = radius * radius * PI;
System.out.println("The area for the circle of" +
"radius" + radius + "is" + area);
Statement(s)
(a)
(b)
F
IGURE
3.1
An
if
statement executes statements if the
boolean-expression
evaluates to
true
.
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
10 System.out.println(
"HiFive"
);
11
12
13 System.out.println(
"HiEven"
);
14 }
15 }
if
(number %
5
==
0
)
check 5
if
(number %
2
==
0
)
check even