Learn Java the Hard Way (Second Edition)

Exercise 15: Making Decisions with If Statements

Hey! I really like this exercise. You suffered through some pretty boring ones there, so it’s time to learn something that is useful and not super difficult.

We are going to learn how to write code that has decisions in it, so that the output isn’t always the same. The code that gets executed changes depending on what the human enters.

 1 import java.util.Scanner;
 3 public class AgeMessages {
 4     public static void main( String[] args ) {
 5         Scanner keyboard = new Scanner(System.in);
 6         int age;
 8         System.out.print( "How old are you? " );
 9         age = keyboard.nextInt();
11         System.out.println( "You are: " );
12         if ( age < 13 ) {
13             System.out.println( "\ttoo young to create a Facebook account" );
14         }
15         if ( age < 16 ) {
16             System.out.println( "\ttoo young to get a driver's license" );
17         }
18         if ( age < 18 ) {
19             System.out.println( "\ttoo young to get a tattoo" );
20         }
21         if ( age < 21 ) {
22             System.out.println( "\ttoo young to drink alcohol" );
23         }
24         if ( age < 35 ) {
25             System.out.println( "\ttoo young to run for President of the U.S." );
26             System.out.println( "\t\t(How sad!)" );
27         }
28     }
29 }

What You Should See

Okay, this is called an “if statement”. An if statement starts with the keyword if, followed by a “condition” in parentheses. The condition must be a Boolean expression that evaluates to either true or false. Underneath that starts a block of code surrounded by curly braces, and the stuff inside the curly braces is indented one more level. That block of code is called the “body” of the if statement.

When the condition of the if statement is true, all the code in the body of the if statement is executed. When the condition of the if statement is false, all the code in the body is skipped. You can have as many lines of code as you want inside the body of an if statement; they will all be executed or skipped as a group.

Notice that when I ran the code, I put in 17 for my age. Because 17 is not less than 13, the condition on line 12 is false, and so the code in the body of the first if statement (lines 13 and 14) was skipped.

The second if statement was also false because 17 is not less than 16, so the code in its body (lines 16 and 17) was skipped, too.

The condition of the third if statement was true: 17 is less than 18, so the body of the third if statement was not skipped; it was executed and the phrase “too young to get a tattoo” was printed on the screen. The remaining if statements in the exercise are all true.

The final if statement contains two lines of code in its body, just to show you what it would look like.

“Learn Java the Hard Way” is ©2013–2016 Graham Mitchell