if-statements

Learn the syntax for if-statements in Java.

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:

Press + to interact
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

...

Get hands-on with 1400+ tech skills courses.