A conditional statement allows your program to make decisions based on certain conditions. Think of it as asking a question: "If this happens, what should I do?" In Java, we use if
, else if
, and else
statements to create these decisions.
if
StatementThe if
statement is the simplest form of a conditional. It checks whether a condition is true. If the condition is true, it executes a block of code.
if (condition) {
// code to be executed if condition is true
}
Let's say you want to check if a number is positive.
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
In this example, number > 0
is the condition. Since 10
is greater than 0
, the message "The number is positive." will be printed.
else if
and else
StatementsSometimes you need to check multiple conditions. You can use else if
to check another condition if the first one is false. If none of the conditions are true, you can use else
to execute a default block of code.
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if none of the conditions are true
}
Let's expand our number example to check if a number is positive, negative, or zero.
int number = -5;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
Imagine you're programming a traffic light system. The traffic light can be red, yellow, or green. Based on the light's color, you need to decide what action to take.
String lightColor = "red";
if (lightColor.equals("green")) {
System.out.println("Go!");
} else if (lightColor.equals("yellow")) {
System.out.println("Slow down!");
} else if (lightColor.equals("red")) {
System.out.println("Stop!");
} else {
System.out.println("Invalid color!");
}
Here is a complete program that checks if a person is eligible to vote based on their age.
public class VotingEligibility {
public static void main(String[] args) {
int age = 17;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
}
}
Write a Java program that checks the temperature and prints whether it's hot, warm, or cold. Use the following conditions:
If the temperature is above 30 degrees, print "It's hot!"
If the temperature is between 15 and 30 degrees, print "It's warm."
If the temperature is below 15 degrees, print "It's cold."
Conditional statements like if
, else if
, and else
are essential for making decisions in your programs. They help your program respond differently based on different conditions, making it more dynamic and interactive. Practice writing these statements with different conditions to become comfortable using them in your programs.