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.
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.
- Open the File Explorer on the left side of the WebIDE.
- Right-click in the
~/projectdirectory and select "New File". - 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 namednumberand assigns it the value 10.if (number > 5): This is theifstatement. The condition isnumber > 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 conditionnumber > 5is 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.
Save the
ConditionalExample.javafile (Ctrl+S or Cmd+S).Open the Terminal at the bottom of the WebIDE. Ensure you are in the
~/projectdirectory. If not, typecd ~/projectand press Enter.Compile the Java file using the
javaccommand:javac ConditionalExample.javaIf there are no errors, this command will create a
ConditionalExample.classfile.Run the compiled Java program using the
javacommand: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.
Open the
ConditionalExample.javafile in the WebIDE editor.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) andisSunny(a boolean, which can be eithertrueorfalse). - The first
ifstatement checks if thetemperaturevariable is greater than 20. - The second
ifstatement checks if theisSunnyvariable istrue.
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.
Save the
ConditionalExample.javafile.Open the Terminal and ensure you are in the
~/projectdirectory.Compile the modified Java file:
javac ConditionalExample.javaRun 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.
- Modify the
ConditionalExample.javafile 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.");
}
}
}
Save the file.
Compile the program again:
javac ConditionalExample.javaRun 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.
Open the
ConditionalExample.javafile in the WebIDE editor.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 variableisWeekend.if (temperature > 20 && isSunny): This condition uses the&&(AND) operator. The code inside the curly braces will only execute if bothtemperature > 20is true andisSunnyis true.if (isSunny || isWeekend): This condition uses the||(OR) operator. The code inside the curly braces will execute if eitherisSunnyis true orisWeekendis 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 > 25ANDisSunny) is true, OR ifisWeekendis true.
Given the current variable values (temperature = 25, isSunny = true, isWeekend = false):
temperature > 20 && isSunny:(25 > 20)is true,isSunnyis true. True && True is True. This condition is true.isSunny || isWeekend:isSunnyis true,isWeekendis false. True || False is True. This condition is true.(temperature > 25 && isSunny) || isWeekend:(25 > 25)is false,isSunnyis 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.
Save the
ConditionalExample.javafile.Open the Terminal and ensure you are in the
~/projectdirectory.Compile the modified Java file:
javac ConditionalExample.javaRun 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.



