If Statements in Java


TL ; DR:






Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast
  
I I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if(conditions) {
    // instructions
}

The keyword if tells Java to execute the code inside the curly braces (where we have our Java comment) only if the conditions defined in the parentheses are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be true or false.

If the boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

boolean isRainy = true;
if(isRainy) {
    System.out.println("I bring an umbrella");
}

The code above prints "I bring an umbrella" since the condition in the parentheses evaluates to true

But this code:

boolean amHungry = false;
if(amHungry) {
    System.out.println("I have breakfast");
}

prints nothing since amHungry evaluates to false.


Assignment
Follow the Coding Tutorial and let's practice with if statements!


Hint
Look at the examples above if you get stuck.


Introduction

If statements are a fundamental concept in programming that allow us to make decisions in our code. They are essential for creating dynamic and responsive programs that can react to different inputs and conditions. Whether you're developing a simple application or a complex system, understanding how to use if statements effectively is crucial.

Common scenarios where if statements are particularly useful include:

Understanding the Basics

Before diving into more complex uses of if statements, it's important to grasp the basic syntax and functionality. An if statement in Java looks like this:

boolean condition = true;
if(condition) {
    // Code to execute if condition is true
}

The condition inside the parentheses is a boolean expression that evaluates to either true or false. If the condition is true, the code block inside the curly braces is executed. If the condition is false, the code block is skipped.

Here's a simple example to illustrate this:

boolean isSunny = true;
if(isSunny) {
    System.out.println("It's a sunny day!");
}

In this example, the message "It's a sunny day!" will be printed because the condition isSunny is true.

Main Concepts

Let's delve deeper into the key concepts and techniques involved in using if statements:

Here's an example that combines these concepts:

int temperature = 25;
boolean isSunny = true;
if(temperature > 20 && isSunny) {
    System.out.println("It's a warm and sunny day!");
}

In this example, the message "It's a warm and sunny day!" will be printed only if both conditions (temperature > 20 and isSunny) are true.

Examples and Use Cases

Let's explore some examples and real-world use cases where if statements are beneficial:

// Example 1: Checking user input
int userAge = 18;
if(userAge >= 18) {
    System.out.println("You are eligible to vote.");
} else {
    System.out.println("You are not eligible to vote.");
}

// Example 2: Validating data
String password = "password123";
if(password.length() >= 8) {
    System.out.println("Password is valid.");
} else {
    System.out.println("Password is too short.");
}

// Example 3: Controlling program flow
boolean isLoggedIn = false;
if(isLoggedIn) {
    System.out.println("Welcome back!");
} else {
    System.out.println("Please log in.");
}

Each example demonstrates how if statements can be used to make decisions based on different conditions.

Common Pitfalls and Best Practices

When working with if statements, it's important to be aware of common mistakes and follow best practices:

Here's an example of refactoring deeply nested if statements:

// Deeply nested if statements
if(condition1) {
    if(condition2) {
        if(condition3) {
            // Code to execute
        }
    }
}

// Refactored using logical operators
if(condition1 && condition2 && condition3) {
    // Code to execute
}

Advanced Techniques

Once you're comfortable with the basics, you can explore advanced techniques such as:

Here's an example of using the ternary operator:

int age = 20;
String eligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
System.out.println(eligibility);

Code Implementation

Let's implement a more comprehensive example that demonstrates the correct use of if statements:

public class Main {
    public static void main(String[] args) {
        // Example: Checking weather conditions
        boolean isRainy = true;
        boolean isWindy = false;
        
        if(isRainy && isWindy) {
            System.out.println("It's rainy and windy. Stay indoors!");
        } else if(isRainy) {
            System.out.println("It's rainy. Bring an umbrella.");
        } else if(isWindy) {
            System.out.println("It's windy. Wear a jacket.");
        } else {
            System.out.println("The weather is clear. Enjoy your day!");
        }
    }
}

This example checks multiple weather conditions and provides appropriate messages based on the conditions.

Debugging and Testing

Debugging and testing are crucial for ensuring that your if statements work as expected:

Here's an example of writing test cases:

public class MainTest {
    public static void main(String[] args) {
        testWeatherConditions(true, true, "It's rainy and windy. Stay indoors!");
        testWeatherConditions(true, false, "It's rainy. Bring an umbrella.");
        testWeatherConditions(false, true, "It's windy. Wear a jacket.");
        testWeatherConditions(false, false, "The weather is clear. Enjoy your day!");
    }
    
    public static void testWeatherConditions(boolean isRainy, boolean isWindy, String expectedMessage) {
        // Simulate the weather conditions
        if(isRainy && isWindy) {
            assert "It's rainy and windy. Stay indoors!".equals(expectedMessage);
        } else if(isRainy) {
            assert "It's rainy. Bring an umbrella.".equals(expectedMessage);
        } else if(isWindy) {
            assert "It's windy. Wear a jacket.".equals(expectedMessage);
        } else {
            assert "The weather is clear. Enjoy your day!".equals(expectedMessage);
        }
    }
}

Thinking and Problem-Solving Tips

When approaching problems related to if statements, consider the following strategies:

Conclusion

In this lesson, we've covered the basics and advanced concepts of if statements in Java. Mastering if statements is essential for writing dynamic and responsive programs. By understanding boolean expressions, comparison operators, and logical operators, you can create complex decision-making logic in your code. Remember to follow best practices, handle all cases, and test your code thoroughly.

Keep practicing and exploring further applications of if statements to enhance your programming skills.

Additional Resources

For further reading and practice problems, check out the following resources: