Skip to content

If-Else Statements

In Java, just like in real life, we often need to make decisions based on certain conditions. If it's raining, we take an umbrella. If it's not, we don't. In programming, we use conditional statements - specifically, if-else statements - to make these kinds of decisions.

If-Else Statements

An if statement in Java performs a test and executes the following code block if the test evaluates to true. Here's an example:

int speed = 20;

if(speed > 10) {
    System.out.println("The robot is moving fast.");
}

In this code, speed > 10 is the test. If it's true (which it is, since 20 is greater than 10), the message "The robot is moving fast." will be printed to the terminal.

An else statement can be added to an if statement to provide code that will be executed if the test is false. Here's an example:

int speed = 20;

if(speed > 30) {
    System.out.println("The robot is moving fast.");
} else {
    System.out.println("The robot is moving at a normal speed or is stationary.");
}

In this case, since speed > 30 is false (20 is not greater than 30), the message "The robot is moving at a normal speed or is stationary." will be printed.

Nested If-Else Statements

We can also nest if-else statements inside each other to make more complex decisions. Here's an example:

int speed = 20;

if(speed > 30) {
    System.out.println("The robot is moving fast.");
} else if(speed > 10) {
    System.out.println("The robot is moving at a normal speed.");
} else {
    System.out.println("The robot is stationary.");
}

In this case, the program first checks if speed > 30. If that's false, it then checks speed > 10. If that's true, it prints "The robot is moving at a normal speed." If it were false, it would print "The robot is stationary."

Tasks

For this week's tasks, we'll be practicing working with if-else statements. In a new Java file named Week3Task1.java, complete the following tasks:

  1. Declare an integer variable named temperature and assign it a value of 20.
  2. Use an if-else statement to print "It's hot." if temperature is above 30, "It's warm" if temperature is above 15, and "It's cold." otherwise.
  3. Try changing the value of temperature and see how the output changes!

Answers

Additional Resources

W3 Schools - If ... Else