π2.3: if Statements
Table of Contents
π This page is a condensed version of CSAwesome Topic 2.3
One-Way Selection: if
If statements (also called conditionals or conditional blocks) are found in all programming languages as a way to choose between different paths in an algorithm. An if statement is a type of selection structure that interrupts the usual sequential execution. It affects the programβs flow of control by executing different segments of code based on the value of a boolean expression (also called the condition).
if
the condition istrue
, then the next statement (or block of statements) will execute.if
the condition isfalse
, then the next statement (or block of statements) is skipped.
Syntax of an if
Statement
An if statement begins with the keyword if
followed by a boolean expression (condition) inside of an open parenthesis (
and a close parenthesis )
and then followed on the next line by either a single statement, or a block of statements. The open curly brace {
and a close curly brace }
are used to group a block of statements together.
β Examples of if
statements for one-way selection:
// Single if statement β body indented
if (boolean expression)
statement;
// Single if statement β body in {}
if (boolean expression) {
statement;
}
// Block if statement β {} REQUIRED!
if (boolean expression) {
statement1;
statement2;
...
statementN;
}
Note that there is no semicolon (
;
) at the end of the boolean expression (condition) in an if statement, because it is not the end of an instruction. Curly braces ({ }
) are used to mark the beginning and end of the conditionalβs body, the block of code thatβs dependent on the condition.
Consider the example below. Imagine that your cell phone wanted to remind you to take an umbrella if
it was currently raining in your area when it detected that you were leaving the house:
boolean isRaining = true;
if (isRaining) {
System.out.println("Take an umbrella! βοΈ");
}
System.out.println("Drive carefully");
The variable
isRaining
is a boolean variable that is eithertrue
orfalse
. If it is true then the messageTake an umbrella!
will be printed and then execution will continue with the next statement which will printDrive carefully
.
Relational Operators in Conditions
Most if statements have a boolean expression that uses relational operators like ==
, !=
, <
, >
, <=
, >=
, as we saw in the last lesson.
For example, (grade > 60.0)
is a boolean expression (rather than just a boolean variable) and can be used to control the if
statement:
double grade = 85.0;
if (grade > 60.0) {
System.out.println("Congrats, you passed!");
}
System.out.println("Summer school is always an option...");
A common mistake in if statements is using =
instead of ==
in the condition. You should always use ==
in the condition of an if statement to test a variable. One equal sign (=
) assigns a value to a variable, and two equal signs (==
) test if a variable has a certain value.
Two-Way Selection: if-else
What if you want to pick between two possibilities?
πͺ If you are trying to decide between two things to do, you might flip a coin and do one thing if it lands as heads, and another if it is tails. This is an example of two-way selection.
A two-way selection involves two connected conditional blocks: an if
statement controlled by a boolean expression (condition), followed by a corresponding else
statement. The program executes the if
body when the condition is true, and the else
body when the condition is false.
Syntax of an if-else
Block
π If you want to decide between two possibilities, use a if
statement followed by else
:
// Block if-else
if (boolean expression) {
statement1;
statement2;
}
else {
otherStatement;
anotherStatement;
}
Note: an
else
block does not specify a boolean expression/condition in parenthesis, because it is simply the alternative path to theif
statement it comes after.
Type the code below, press run, and then:
- Change
isHeads
tofalse
. - See what prints before
"after conditional"
.
boolean isHeads = true;
if (isHeads) {
System.out.println("Let's go to the game");
}
else {
System.out.println("Let's watch a movie");
}
System.out.println("after conditional");
Common Errors with Conditional Blocks
Here are some rules to follow with if statements to avoid some common errors:
-
Always use curly braces (
{
and}
) to enclose the block of statements under the if condition. Java doesnβt care if you indent the codeβit goes by the{ }
. -
Donβt put in a semicolon
;
after the first line of the if statement,if (test);
. Theif
statement is a multiline block of code that starts with theif
condition and then{
the body of the if statement}
. -
Always use
==
, not=
, in the condition of an if statement to test a variable. One=
assigns, two==
tests! -
The
else
statement matches with the closestif
statement. If you want to match anelse
with a differentif
statement, you need to use curly braces to group theif
andelse
together.
Summary
-
(AP 2.3.A.1) Selection statements change the sequential execution of statements.
-
(AP 2.3.A.2) An if statement is a type of selection statement that affects the flow of control by executing different segments of code based on the value of a Boolean expression.
-
(AP 2.3.A.3) A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition. In this case, the body is executed only when the Boolean expression is true.
-
if statements test a boolean expression and if it is true, go on to execute the body which is the following statement or block of statements surrounded by curly braces (
{}
) like below.
if (boolean expression){
Do Statement1;
Do Statement2;
...
Do StatementN;
}
-
Relational operators (
==
,!=
,<
,>
,<=
,>=
) are used in boolean expressions to compare values and arithmetic expressions. - If statements can be followed by an associated else part to form a 2-way branch:
if (boolean expression){ Do statement; } else { Do other statement; }
- (AP 2.3.A.4) A two-way selection (if-else statement) is used when there are two segments of codeβone to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.