Search⌘ K

if-statements

Explore how to use if statements to execute code based on boolean conditions in Java. Understand syntax, implement else if and else branches, and practice with exercises including temperature checks, robot navigation, and coin flips.

We'll cover the following...

The keyword if can be used to run a block of code only if some condition has the boolean value true. The syntax is like that of C or Javascript: the conditional expression must be wrapped in parentheses, and the statements to be executed should be in curly braces. If you are familiar with those languages, you may wish to skip this section.

Here are a few examples:

Java
class IfExamples {
public static void main(String args[]) {
if(true) {
System.out.println("This code gets executed.");
}
if(false) {
System.out.println("This code does not.");
}
if(5 > 3) {
System.out.println("This code gets executed, too.");
}
if(3 > 5) {
System.out.println("This code does not.");
}
}
}

Exercise: thermometer

Write an if-statement in the following code that checks if the ...