if Statements
Paul Ngugi
Posted on May 2, 2024
An if statement is a construct that enables a program to specify alternative paths of execution. Java has several types of selection statements: one-way if statements, two-way if-else statements, nested if statements, multi-way if-else 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:
if (boolean-expression) {
statement(s);
}
The flowchart 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 denotes a Boolean condition and a rectangle box represents statements.
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 b above. 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).
The block braces can be omitted if they enclose a single statement. For example, the following statements are equivalent.
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.
Here's 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.
Posted on May 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.