Conditional Statements
Conditional statements are used to perform different actions based on different conditions. They allow a program to take different paths during execution based on logical conditions.
if
Statement
The if
statement is used to execute a block of code only if a specified condition is true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
int number = 10;
if (number > 0) {
System.out.println("The number is positive");
}
else
Statement
The else
statement is used with if
to execute a block of code if the condition in the if
statement is false.
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example:
int number = -10;
if (number > 0) {
System.out.println("The number is positive");
} else {
System.out.println("The number is negative");
}
else if
Statement
The else if
statement allows you to test multiple conditions. If the first if
condition is false, it checks the next else if
condition. It can have multiple else if
statements, and an optional else
block for the default case.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the conditions are true
}
Example:
int number = 0;
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");
}
switch
Statement
The switch
statement allows a variable to be tested for equality against a list of values, known as “cases”. When a match is found, the corresponding block of code is executed. The break
statement is used to exit the switch
after executing the matched case.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
default:
// Code to execute if no cases match
}
Example:
int day = 2;
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
}