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.java
file 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) 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.
-
Save the ConditionalExample.java
file.
-
Open the Terminal and ensure you are in the ~/project
directory.
-
Compile the modified Java file:
javac ConditionalExample.java
-
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.
- 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.");
}
}
}
-
Save the file.
-
Compile the program again:
javac ConditionalExample.java
-
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.