If Statements
tutorial processing if-statements- Booleans
- Relational Operators
- Boolean Operators
- If Statements
- Else Statements
- Else-If Statements
- If Else-If Else Combinations
- Learn More
- Homework
Now you know how to call functions, use variables, and create your own variables and functions.
Youâve seen that values have different types. A type tells the computer what kind of data a value is, or what type of value a variable holds. So far youâve mostly worked with the float
type.
This tutorial introduces the boolean
type, which can only hold two possible values: true
or false
. This tutorial also introduces if statements, which allow you to perform different actions depending on the value of a boolean.
Booleans
Remember that a type tells the computer what kind of value a variable will hold. For example, the int
type holds whole numbers, the float
type holds decimal numbers, and the String
type holds text. You create a variable by giving it a type, a name, and then a value:
int catLives = 9;
float accountBalance = -123.45;
String message = "Happy Coding!";
You can create a boolean
variable the same way, but it can only hold two possible values: true
or false
.
boolean isCodingFun = true;
This might not seem very useful yet, but it will become more handy in a couple paragraphs. Keep reading!
Relational Operators
Boolean
variables wouldnât be very useful if you had to decide their values ahead of time. Instead, you can obtain boolean
values through relational operators. You might have called these inequalities in algebra class, where you compared two sides with symbols like <
less than, >
greater than, or ==
equal to. Hereâs an example:
float score = 95;
boolean isGradeA = score >= 90;
This code creates a float
variable named score
and sets it equal to 95
. It then creates a boolean
variable named isGradeA
and sets it equal to the result of the inequality score >= 90
. In this case, the inequality is true
because 95
is greater than 90
. So at the end of this code, isGradeA
is holding the boolean
value of true
.
If that line of code is confusing, try reading the right side first. First you take the inequality score >= 90
and get a boolean
value from it (in this case, true
), and then you point the isGradeA
variable to that value.
Boolean Operators
Similar to how you can add two float
values using the +
operator to get a third float
value, or subtract them using the -
operator, you can also operate on two boolean
values to get a third boolean
value.
And
You can combine two boolean
values using the and operator, which looks like two ampersands: &&
. The and operator evaluates to true
whenever the two boolean
values on either side of it are also true
.
boolean canSwim = true;
boolean canFly = true;
boolean isDuck = canSwim && canFly;
The isDuck
variable will only be true
when both canSwim
and canFly
are also true. If either one of them is false, then isDuck
will also be false.
Again, it might make more sense to read the right side first. First the code evaluates the &&
operator, which creates a boolean
value of true
. Then it points the isDuck
variable to that value.
Or
The or operator evaluates to true if either of the two boolean
values on either side of it is true
.
To use the or operator, type two pipes ||
(theyâre above the enter key, or shift + \
) between two boolean
values:
boolean isTodaySaturday = true;
boolean isTodaySunday = false;
boolean isTodayWeekend = isTodaySaturday || isTodaySunday;
The isTodayWeekend
variables will be true
if either the isTodaySaturday
or isTodaySunday
variables are true
.
First the code evaluates the ||
operator which creates a boolean
value (in this case itâs true
), and then it points the isTodayWeekend
variable to that value.
Not
In addition to operating on two boolean
values, you can also calculate the opposite of a single boolean
value. The opposite of true
is false
, and the opposite of false
is true
.
This is called the not operator, and you use it by typing an exclamation point !
before the value you want to switch.
boolean sinks = !canSwim;
boolean falls = !canFly;
boolean isTodayWeekday = !isTodayWeekend;
Each line of this code evaluates the !
operator which creates a new boolean
value based on the opposite of whatever follows it, and then it points a boolean
variable to that value.
Combining Operators
You can also combine these operators to form more complicated logic. So you can do things like this:
boolean isMammal = !canSwim && !canFly;
First this code takes the opposite of the canSwim
and canFly
variables to create two new boolean
values. It then takes those values and feeds them into the &&
operator, which creates yet another boolean
value. Then it points the isMammal
variable to that value.
(If this bothers you because it doesnât account for animals like bats, beavers, and dolphins⊠check out the homework!)
There is a whole field of study devoted to boolean
logic, so check that out if it sounds interesting. But for now, keep in mind that boolean
values contain true
or false
, and you can use operators like &&
, ||
, and !
on them.
If Statements
An if
statement checks a boolean
value and only executes a block of code if that value is true
.
To write an if
statement, write the keyword if
, then inside parentheses ()
insert a boolean
value, and then in curly brackets {}
write the code that should only execute when that value is true
. That code is called the body of the if
statement.
Hereâs an example that draws a congratulations message, but only if your grade is an A:
size(200, 100);
float score = 95;
boolean isGradeA = score >= 90;
if (isGradeA) {
background(0, 255, 0);
fill(0);
textSize(18);
text("Congratulations!", 30, 55);
}
This code uses an if
statement to check whether isGradeA
is true
, and if it is, it draws a green background, changes the fill color to black and the text size to 18
, and then writes "Congratulations!"
on the screen.
Since score
is 95
(and 95
is greater than 90
), then you see the congratulations message:
If isGradeA
is false
(if score
is less than 90
), then the program doesnât do anything. Try changing score
to 85
, and youâll see a blank window:
Since isGradeA
is now false
, the body of the if
statement is not executed, and it skips over all of the code inside the body.
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
Boolean Expressions
So far, all of the examples have separated the inequality and the if
statement into two steps: the code first created a boolean
variable from an inequality, and then it used that variable in an if
statement. But you can combine them into a single step:
size(200, 100);
float score = 95;
if (score >= 90) {
background(0, 255, 0);
fill(0);
textSize(18);
text("Congratulations!", 30, 55);
}
This does the exact same thing as the old code, except now the inequality (which evaluates to a boolean
value) is inside the if
statement instead of being split into its own step. Either approach is fine, so you should use whichever style makes the most sense to you.
Else Statements
An if
statement executes some code if its boolean
value is true
, and it skips that code if the boolean
value is false
. But what if you want to do one thing if the value is true
and a different thing if itâs false
? Sounds like a job for an else
statement!
To use an else
statement, type the else
keyword after an if
statement, and then inside curly brackets {}
put the code you want to execute when the if
statementâs boolean
evaluates to false
:
size(200, 100);
fill(0);
textSize(18);
float score = 85;
if (score >= 90) {
background(0, 255, 0);
text("Congratulations!", 30, 55);
}
else {
background(255, 0, 0);
text("Study more!", 50, 55);
}
This code uses an if
statement to check whether score
is greater than or equal to 90
. Since 85
is less than 90
, that inequality is false
, so the code inside the if
statement is skipped. Instead, the program jumps to the code inside the body of the else
statement, which draws a red background and displays the âStudy more!â message.
You can think about the code like this: âIf the score is greater than or equal to 90, then display the âCongratulations!â message. Otherwise, display the âStudy more!â message instead.â
Else-If Statements
An if
statement executes some code if its boolean
evaluates to true
, and an else
statement executes code if it evaluates to false
. But what if you want to take different actions depending on multiple cases? This is where else-if
statements come in handy.
An else-if
statement is like a mix between an else
statement and an if
statement. You put an else-if
statement after an if
statement, and if the if
statement evaluates to false
, then the else-if
statementâs boolean
is evaluated:
size(200, 100);
fill(0);
textSize(18);
float score = 85;
if (score >= 90) {
background(0, 255, 0);
text("Congratulations!", 30, 55);
}
else if (score >= 80) {
background(0, 100, 255);
text("Good job!", 60, 55);
}
This code uses an if
statement to check whether score
is greater than or equal to 90
. Since 85
is less than 90
, that inequality is false
, so the code inside the if
statement is skipped. The program jumps down to the else-if
statement and checks the boolean
expression inside the else-if
statement. Since 85
is greater than 80
, the inequality is true
, and the code inside the body of the else-if
is executed. The code then draws a blue background and and displays the âGood job!â message.
You can think about the code like this: âIf the score is greater than or equal to 90, then display the âCongratulations!â message. Otherwise check whether the score is greater than or equal to 80. If it is, then display the `Good job!â message instead.â
If score
was 95
, then only the code inside the body of the if
statement would run. The code inside the else-if
statement would be skipped. And if score
was 75
, then the boolean
expressions of both the if
statement and the else-if
statement would evaluate to false
, so neither one of their bodies would be executed.
If Else-If Else Combinations
You can follow an if
statement with multiple else-if
statements, and you can follow an else-if
statement with an else
statement. So you could expand your program to detect every grade:
size(200, 100);
fill(0);
textSize(18);
float score = 55;
if (score >= 90) {
background(0, 255, 0);
text("Congratulations!", 30, 55);
}
else if (score >= 80) {
background(0, 100, 255);
text("Good job!", 60, 55);
}
else if (score >= 70) {
background(255, 255, 0);
text("Just okay.", 60, 55);
}
else if (score >= 60) {
background(255, 128, 0);
text("Not good!", 60, 55);
}
else {
background(255, 0, 0);
text("Study more!", 50, 55);
}
This code uses a series of if
, else if
and else
statements to run this logic:
- Is
score >= 90
?- If so, show the âCongratulations!â message and stop checking any other conditions.
- If not, keep checking.
- Is
score >= 80
?- If so, show the âGood job!â message and stop checking any other conditions.
- If not, keep checking.
- Is
score >= 70
?- If so, show the âJust okay.â message and stop checking any other conditions.
- If not, keep checking.
- Is
score >= 60
?- If so, show the âNot good!â message and stop checking any other conditions.
- If not, show the âStudy more!â message.
Try changing the score
variable to see the different messages.
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
Avoiding Unnecessary Checks
Keep in mind that only one body of code is entered in a series of if else-if else
statements. As soon as the code enters one of the if
or else-if
statements, it stops checking subsequent else-if
statements.
Look at this line of code, from the above program:
else if (score >= 80) {
Notice that the code only checks whether score >= 80
. But for the grade to be a B, it also has to be < 90
. Why doesnât the code also check for that?
The code doesnât check to make sure that score < 90
, because it already knows that it is. If score
was >= 90
, then the first if
statement would have been entered, and the code wouldnât even reach this line.
Think about it this way: first the code checks whether the grade is an A. If it is, then it displays the âCongratulations!â message and doesnât check any other grades since it already knows the grade is an A. If itâs not an A, then it knows that score < 90
and it keeps checking other grades.
Thatâs why the code can check whether the grade is a B by only checking whether score > 80
. It it is, then it displays the âGood job!â message and doesnât check against any other grades since it already knows the grade is a B. If itâs not a B, then it knows that score < 80
, and it continues that pattern for the rest of the program.
Learn More
- The
if-then
andif-then-else
Statements - Oracleâs Java Tutorials - Equality, Relational, and Conditional Operators - Oracleâs Java Tutorials
- Java
If ... Else
- W3Schools if
- Processing Referenceelse
- Processing Reference
Homework
- Expand the
boolean
example to work for more animals. Write ashowAnimalType
function that takes a set ofboolean
parameters (as many as you want!) and shows a message that explains whether the animal is a mammal, bird, reptile, amphibian, or fish. How would you represent a bat (which can fly but isnât a bird) or a penguin (which canât fly but is a bird)? If you want an advanced challenge, do a google search for âanimal identification keyâ for some handy guides. - Write a greeting program that shows a different message depending on what time of day it is (morning, afternoon, evening, or night).
- Create a program that uses
boolean
logic to determine the outcome of a flowchart like this one. If you want an advanced challenge, try this one!
Comments and Questions
Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!