DEV Community

Cover image for if Statements
Paul Ngugi
Paul Ngugi

Posted on

if Statements

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);
}
Enter fullscreen mode Exit fullscreen mode

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.

Image description

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);
}
Enter fullscreen mode Exit fullscreen mode

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).

Image description

The block braces can be omitted if they enclose a single statement. For example, the following statements are equivalent.

Image description

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.

Image description

Top comments (0)