How to Check If a Condition Is True in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a condition is true in Java using conditional expressions. This fundamental programming concept allows your programs to make decisions and behave differently based on various situations. You will start by writing a simple conditional expression using an if statement to execute code only when a specific condition is met.

Building upon the basics, you will then explore how to test conditions using variables, making your programs more dynamic. Finally, you will learn how to handle more complex conditions, enabling your Java applications to make sophisticated decisions.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java/BasicSyntaxGroup -.-> java/operators("Operators") java/BasicSyntaxGroup -.-> java/booleans("Booleans") java/BasicSyntaxGroup -.-> java/variables("Variables") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/BasicSyntaxGroup -.-> java/output("Output") subgraph Lab Skills java/operators -.-> lab-559943{{"How to Check If a Condition Is True in Java"}} java/booleans -.-> lab-559943{{"How to Check If a Condition Is True in Java"}} java/variables -.-> lab-559943{{"How to Check If a Condition Is True in Java"}} java/if_else -.-> lab-559943{{"How to Check If a Condition Is True in Java"}} java/output -.-> lab-559943{{"How to Check If a Condition Is True in Java"}} end

Write a Simple Conditional Expression

In this step, we will learn about conditional expressions in Java. Conditional expressions allow your program to make decisions based on certain conditions. This is a fundamental concept in programming, enabling your programs to behave differently depending on the situation.

Think of it like this: "IF it is raining, THEN take an umbrella." The condition is "it is raining," and the action is "take an umbrella." In Java, we use if statements to achieve this.

Let's start by creating a new Java file.

  1. Open the File Explorer on the left side of the WebIDE.
  2. Right-click in the ~/project directory and select "New File".
  3. Name the new file ConditionalExample.java.

Now, let's write some code in this file. Copy and paste the following code into the ConditionalExample.java file:

public class ConditionalExample {
    public static void main(String[] args) {
        int number = 10;

        if (number > 5) {
            System.out.println("The number is greater than 5.");
        }
    }
}

Let's break down this code:

  • public class ConditionalExample: This declares our class, matching the file name.
  • public static void main(String[] args): This is the main method where our program starts execution.
  • int number = 10;: This declares an integer variable named number and assigns it the value 10.
  • if (number > 5): This is the if statement. The condition is number > 5. The code inside the curly braces {} will only execute if this condition is true.
  • System.out.println("The number is greater than 5.");: This line will print the message to the console if the condition number > 5 is true.

Since number is 10, and 10 is indeed greater than 5, the condition number > 5 is true. Therefore, the message "The number is greater than 5." should be printed.

  1. Save the ConditionalExample.java file (Ctrl+S or Cmd+S).

  2. Open the Terminal at the bottom of the WebIDE. Ensure you are in the ~/project directory. If not, type cd ~/project and press Enter.

  3. Compile the Java file using the javac command:

    javac ConditionalExample.java

    If there are no errors, this command will create a ConditionalExample.class file.

  4. Run the compiled Java program using the java command:

    java ConditionalExample

You should see the output:

The number is greater than 5.

This confirms that our simple conditional expression worked as expected. In the next step, we will explore how to use variables within our conditions.

Test Condition with Variables

In this step, we will expand on our understanding of conditional expressions by using variables within the conditions. This makes our programs more dynamic, as the outcome can change based on the values stored in variables.

Let's modify the ConditionalExample.java file we created in the previous step.

  1. Open the ConditionalExample.java file in the WebIDE editor.

  2. Replace the existing code with the following:

public class ConditionalExample {
    public static void main(String[] args) {
        int temperature = 25;
        boolean isSunny = true;

        if (temperature > 20) {
            System.out.println("It's a warm day.");
        }

        if (isSunny) {
            System.out.println("It's sunny today.");
        }
    }
}

In this updated code:

  • We have two variables: temperature (an integer) and isSunny (a boolean, which can be either true or false).
  • The first if statement checks if the temperature variable is greater than 20.
  • The second if statement checks if the isSunny variable is true.

Since temperature is 25 (which is greater than 20) and isSunny is true, both conditions should evaluate to true, and both messages should be printed.

  1. Save the ConditionalExample.java file.

  2. Open the Terminal and ensure you are in the ~/project directory.

  3. Compile the modified Java file:

    javac ConditionalExample.java
  4. Run the compiled program:

    java ConditionalExample

You should see the following output:

It's a warm day.
It's sunny today.

This demonstrates how you can use variables directly within your if conditions. The program's output changes based on the current values of the temperature and isSunny variables.

Now, let's change the values of the variables to see how the output changes.

  1. Modify the ConditionalExample.java file again. Change the values of the variables:
public class ConditionalExample {
    public static void main(String[] args) {
        int temperature = 15; // Changed temperature
        boolean isSunny = false; // Changed isSunny

        if (temperature > 20) {
            System.out.println("It's a warm day.");
        }

        if (isSunny) {
            System.out.println("It's sunny today.");
        }
    }
}
  1. Save the file.

  2. Compile the program again:

    javac ConditionalExample.java
  3. Run the program:

    java ConditionalExample

This time, since temperature is 15 (not greater than 20) and isSunny is false, neither condition is true, and you should see no output.

This illustrates the power of using variables in conditional statements โ€“ the program's behavior is determined by the data it is processing.

Handle Complex Conditions

In this step, we will learn how to combine multiple conditions to create more complex decision-making logic in our Java programs. We can use logical operators like && (AND) and || (OR) to achieve this.

Let's modify the ConditionalExample.java file one more time.

  1. Open the ConditionalExample.java file in the WebIDE editor.

  2. Replace the existing code with the following:

public class ConditionalExample {
    public static void main(String[] args) {
        int temperature = 25;
        boolean isSunny = true;
        boolean isWeekend = false;

        // Condition using AND (&&)
        if (temperature > 20 && isSunny) {
            System.out.println("It's a warm and sunny day.");
        }

        // Condition using OR (||)
        if (isSunny || isWeekend) {
            System.out.println("It's either sunny or the weekend.");
        }

        // Condition using AND and OR
        if ((temperature > 25 && isSunny) || isWeekend) {
             System.out.println("It's very warm and sunny, or it's the weekend.");
        }
    }
}

Let's look at the new parts:

  • boolean isWeekend = false;: We've added a new boolean variable isWeekend.
  • if (temperature > 20 && isSunny): This condition uses the && (AND) operator. The code inside the curly braces will only execute if both temperature > 20 is true and isSunny is true.
  • if (isSunny || isWeekend): This condition uses the || (OR) operator. The code inside the curly braces will execute if either isSunny is true or isWeekend is true (or both).
  • if ((temperature > 25 && isSunny) || isWeekend): This condition combines both && and ||. The parentheses () are used to group conditions, just like in mathematics. This condition is true if (temperature > 25 AND isSunny) is true, OR if isWeekend is true.

Given the current variable values (temperature = 25, isSunny = true, isWeekend = false):

  • temperature > 20 && isSunny: (25 > 20) is true, isSunny is true. True && True is True. This condition is true.
  • isSunny || isWeekend: isSunny is true, isWeekend is false. True || False is True. This condition is true.
  • (temperature > 25 && isSunny) || isWeekend: (25 > 25) is false, isSunny is true. False && True is False. False || False is False. This condition is false.

So, we expect the first two messages to be printed, but not the third.

  1. Save the ConditionalExample.java file.

  2. Open the Terminal and ensure you are in the ~/project directory.

  3. Compile the modified Java file:

    javac ConditionalExample.java
  4. Run the compiled program:

    java ConditionalExample

You should see the following output:

It's a warm and sunny day.
It's either sunny or the weekend.

This confirms that our complex conditions using && and || worked correctly. You can change the values of temperature, isSunny, and isWeekend and recompile and run the program to see how the output changes based on the different combinations of conditions.

Understanding how to combine conditions is crucial for writing programs that can handle various scenarios and make more sophisticated decisions.

Summary

In this lab, we began by learning the fundamental concept of conditional expressions in Java, which allow programs to make decisions based on conditions. We created a simple Java file named ConditionalExample.java and wrote code demonstrating a basic if statement. This involved declaring an integer variable and using an if statement with a condition (number > 5) to control the execution of a print statement. We learned how the code within the if block only executes when the specified condition evaluates to true.

We then proceeded to test conditions using variables, building upon the basic if statement. This involved using variables within the conditional expression to make the decision-making process dynamic. Finally, we explored handling complex conditions, which likely involved combining multiple conditions using logical operators (like && for AND, || for OR, and ! for NOT) to create more sophisticated decision-making logic within our Java programs.