Java Decision Making Statements: If-Else-If Ladder, Nested If, Switch, and Break
Java Decision Making Statements - If-Else, Switch, and Break
Control flow statements in Java are divided in two parts: Decision Making and Iteration. In this tutorial decision making (if-else, switch, and break) statements will be discussed.
Before start discussing Java's control flow statements it would be nice to know that Java is a structured programming language and Java program statements can be executed sequentially, conditionally (with the help of if-else, and switch), iteratively (with the help of loops) or by following a combination of all depending upon the program logic. Conditional and iterative execution of Java program's statements is done by control flow statements. Conditional statements in Java include if-else and switch-case statements discussed in this tutorial.
Decision Making in Java
To facilitate conditional control flow in Java there are relational and logical operators to form a conditional expression that returns either true
or false
. Words true
and false
look like keywords but they are boolean literals actually and cannot be used as identifiers in Java programs. Java program decides the execution path on basis of the truth or falsehood of conditional expression.
Java Statements and Blocks
Zero or more statements enclosed in curly braces in a Java program make a block of statements. A block is treated as a single unit and can be used where a single statement is allowed. In fact, a block is a statement but this is a compound statement. We will soon come to know the worth of a block when we will have to control more than one statement by decision making constructs of Java.
Java If Statement
An if
statement is the most basic Java control flow statement you will see in Java programs along with an optional else part. Following is the general syntax of if statement:
if (booleanExpression) statement-1; if (booleanExpression) { statement-1; statement-2; . . . statement-n; }
The booleanExpression
in parentheses must return a boolean true
or false
or Boolean
(boolean wrapper). The expression can be a relational or logical expression or a function call that returns a boolean
literal. Above syntax will execute statement-1
to statement-n
if the booleanExpression
in parentheses returns true
, nothing otherwise.
By default if
controls only one statement, therefore if you wish to control only one statement by if
then you need not to enclose the only statement within curly braces. But, it is good to use braces every time with if
because it increases readability of your program. If there are two or more statements to be controlled by if
conditional then they all must be enclosed in curly braces. A set of statements enclosed in braces is called a block or a compound statement. For demonstration, consider the following example program: