Conditional statements allow your program to make decisions and execute different blocks of code based on certain conditions.
if
statement is used to execute a block of code if a certain condition is true. If the condition is false, the code block is skipped.class IfExample{
public static void main(String[] args) {
int age = 25;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
}
}
Output: "You are eligible to vote.”
if-else
statement allows you to specify an alternative block of code to execute when the condition is falseclass IfElseExample{
public static void main(String[] args) {
int temperature = 25;
if (temperature > 30) {
System.out.println("It's a hot day.");
} else {
System.out.println("It's a moderate day.");
}
}
}
Output: "It's a moderate day.”
switch
statement provides an alternative way to perform multiple conditional checks based on the value of an expression.class SwitchExample {
public static void main(String[] args) {
String dayOfWeek = "Tuesday";
switch (dayOfWeek) {
case "Monday":
System.out.println("It's the beginning of the week.");
break;
case "Tuesday":
System.out.println("It's a regular workday.");
break;
case "Saturday":
case "Sunday":
System.out.println("It's the weekend!");
break;
default:
System.out.println("Invalid day.");
}
}
}
Output: "It's a regular workday.”
Looping statements allow you to repeat a block of code multiple times based on a condition.
while
loop repeatedly executes a block of code as long as the condition is true.class WhileExample{
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5