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.
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
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
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
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
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.
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.
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