Learn how to control program flow based on a condition.
Conditional Branching Basics
Branches allow a Java program to alter the flow of execution and run one piece of code instead of another. The figure below shows how a Java program flows without branches:
Java program without branches
A Java program without branches executes one statement at a time from start to end. Although technically there is nothing wrong with the program in the figure, it is extremely limited in terms of what it can do.
More specifically, there is no way for it to take a different path of execution. The following figure shows how a branch gives the program more freedom:
Java program with branches containing a conditional branch.
The if-else statement
The if-else statement allows you to conditionally execute one section of code or another. Because of its simplicity and wide range of usefulness, the if-else statement is the most commonly used branch in Java.
The syntax for the if-else statement follows:
if (Condition)
Statement1
else
Statement2
If the Boolean Condition is true, Statement1 is executed; otherwise Statement2 is executed.
Following is a simple example:
if (tired)
timeForBed = true;
else
timeForBed = false;
If the Boolean variabletired is true, the first statement is executed and timeForBed is set to true. Otherwise the second statement is executed and timeForBed is set to false. The else part of the if-else statement is optional. In other words, you can leave it off if you have only a single statement that you want to execute conditionally. It is also possible to link together a series of if-else statements to get the effect of multiple branches. Variables: Variables are locations in memory that are used to store information.
You can think of variables as storage containers designed to hold data of a certain type.
You are not limited to executing an individual line of code with the
if-else statement.
To execute multiple lines of code you can use a compound statement, which is a block of code surrounded by curly braces
({}). An if-else statement interprets a compound statement as a single statement. Following is an example that demonstrates using a compound statement: