If Statement
Note: It is considered good programming practice to always use block notation { … } when using an if statement, even if a there is just one statement in the block.
The statements in a Java main method normally run, or execute, one at a time in the order they are found from top to bottom. If statements (also called conditionals or selection) change the flow of control through the program so that some code is only run when something is true. In a simple if statement, if the condition is true, then the statements in the if-block will execute. If the condition is false, then statements in the if-block will be skipped, and control will be passed to the statement following the simple if statement.
A conditional uses the keyword if
followed by a boolean expression inside of an open parenthesis “("
and a close parenthesis “)"
, and then followed by a block of statements. The single statement or block of statements are only executed if the condition is true. The open curly brace {
and a close curly brace }
are used to group a block of statements together.
// A single if statement
if (boolean expression)
Do stuff; // this is valid, but not recommended
// Or a single if with {...}
if (boolean expression)
{
Do stuff; // this is considered good programming practice
}
// A block if statement: { } required
if (boolean expression)
{
Do stuff 1;
Do stuff 2;
...
Do stuff 3;
}
Let’s look at a simple if statement using a boolean variable. What do you think will be printed? Try changing the boolean variable to false, what happens then?
You don’t have to just use a boolean variable in an if statement. You may also use operators to check if the comparison between two values is true or not. In the latter case, you are using a boolean expression.
Fix the code below so that the statement prints what is expected.
You can pair an if-statement with an else statement. This will let you pick one path or the other, affecting the control flow of the program.
// A block if/else statement
if (some boolean expression or comparison)
{
do stuff 1;
do stuff 2;
}
else
{
do other stuff;
and more stuff;
}
The following chart demonstrates a flow chart, which picks between two options and decides which lines of code should run.
You can combine as many if statements as you need inside of other if statements. Say, you want something to happen if it is sunny and if is also hot, otherwise something else should happen if it sunny but it is not hot.
Try to fix the code below to reflect that.