2. If Statements¶
2.1. Objectives¶
- Identify and use the
if
statement in Java
2.2. Time Goal¶
- 15 minutes on this section
2.3. Key Terms¶
- conditional statement
- A statement that uses a condition to determine which statements to execute.
- block
- A sequence of statements, surrounded by braces, that generally runs as the result of a condition.
- branch
- One of the alternative blocks after a conditional statement. For example, an if-else statement has two branches.
2.4. Exercises¶
Note
To write useful programs, we almost always need to check conditions and react accordingly. Conditional statements give us this ability.
The simplest conditional statement in Java is the if
statement:
if (x > 0) {
System.out.println("x is positive");
}
The expression in parentheses is called the condition. If it is true, the statements in braces get executed.
If the condition is false, execution skips over that block of code. The condition in parentheses can be any boolean
expression.
A second form of conditional statement has two possibilities, indicated by if and else. The possibilities are called branches, and the condition determines which one gets executed:
if (x % 2 == 0) {
System.out.println("x is even");
} else {
System.out.println("x is odd");
}
If the remainder when x is divided by 2 is zero, we know that x is even, and the program displays a message to that effect. If the condition is false, the second print statement is executed instead. Since the condition must be true or false, exactly one of the branches will run.
The braces are optional for branches that have only one statement. So we could have written the previous example this way:
if (x % 2 == 0)
System.out.println("x is even");
else
System.out.println("x is odd");
However, it’s better to use braces – even when they are optional – to avoid making the mistake of adding statements to an if
or else
block
and forgetting to add the braces. This code is misleading because it’s not indented correctly:
if (x > 0)
System.out.println("x is positive");
System.out.println("x is not zero");
Since there are no braces, only the first println is part of the if statement. Here is what the compiler actually sees:
if (x > 0) {
System.out.println("x is positive");
}
System.out.println("x is not zero");
As a result, the second println runs no matter what. Even experienced programmers make this mistake; search the web for Apple’s “goto fail” bug.
In all previous examples, notice how there is no semicolon at the end of the if or else lines. Instead, a new block should be defined using curly braces. Another common mistake is to put a semicolon after the condition, like this:
int x = 1;
if (x % 2 == 0); { // incorrect semicolon
System.out.println("x is even");
}
This code will compile, but the program will output “x is even” regardless what value x is. Here is the same incorrect code with better formatting:
int x = 1;
if (x % 2 == 0)
; // empty statement
{
System.out.println("x is even");
}
Because of the semicolon, the if statement compiles as if there are no braces, and the subsequent block runs independently. As a general rule, each line of Java code should end with a semicolon or brace – but not both.
The compiler won’t complain if you omit optional braces or write empty statements. Doing so is allowed by the Java language, but it often results in bugs that are difficult to find. Development tools like Checkstyle (see Appendix A.5) can warn you about these and other kinds of programming mistakes
Java statements normally execute one at a time from top to bottom. If you want a statement to only execute when something is true use a conditional. Something that can only be true or false is called a Boolean. If the condition is true then the next statement or a block of statements will execute. If the condition is false then the next statement or block of statements is skipped.
Note
A conditional uses the keyword if
followed by Boolean expression inside of an open parenthesis (
and a close parenthesis )
and then followed by a single statement or block of statements. The single statement or block of statements are only executed if the condition is true. A block of statements is enclosed by an open curly brace {
and a close curly brace }
.
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. This type of thing is going to become more common in the future and it is an area of research called Human Computer Interaction (HCI) or Ubiquitous Computing (computers are everywhere).
public class Test1
{
public static void main(String[] args)
{
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 either true or false. If it is true then the message Take an umbrella!
will be printed and then execution will continue with the next statement which will print Drive carefully
. Run the code above to see this.
Try changing the code above to boolean isRaining = false;
. What will it print?
What if you want to pick between two possibilities? If you are trying to decide between a couple of things to do, you might do one thing if a coin flip is heads and another if it is tails. In this case use the if keyword followed by a statement or block of statements and then the else keyword also followed by a statement or block of statements.
Note
The else will only execute if the condition is false.
public class Test2
{
public static void main(String[] args)
{
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");
}
}
If isHeads
is true it will print Let's go to the game
and then after conditional
. Run the code above to see this.
Try changing the code above to boolean isHeads = false;
. What line will be printed before the after conditional
?
Note
An if will only execute one single statement following it unless there is a block of statements enclosed in a pair of open and closed curly braces {
and }
. Java doesn’t care if you indent the code to show what you intend!
The code below doesn’t work as expected. Fix it so that “Wear gloves” prints only when isCold is true.
public class Test
{
public static void main(String[] args)
{
boolean isCold = false;
if (isCold)
System.out.println("Wear a coat");
System.out.println("Wear gloves");
System.out.println("Bye");
}
}
Check your understanding
Q-18: What is the value of grade when the following code executes and score is 93?
if (score >= 90) grade = "A";
if (score >= 80) grade = "B";
if (score >= 70) grade = "C";
if (score >= 60) grade = "D";
else grade = "E";
Q-19: Which of the following is equivalent to the code segment below?
if (x > 2)
x = x * 2;
if (x > 4)
x = 0;
Note
Try to solve each of the following. Click the Check Me button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren’t needed in the correct solution.
System.out.println("You are right!");
System.out.println("Your guess is too high");
else if (guess == answer)
System.out.println("Your guess is too low");
int guess = 10;
int answer = 5;
if (guess < answer)
else
System.out.println("7:00am");
public class Test1
{
if (!weekend)
else
boolean weekend = false;
public static void main(String[] args)
{
System.out.println("10:00am");
}
}