Decision making statements in Java are used to make decisions based on certain conditions.Â
The most commonly used decision making statements are:
if-else statement: The if-else statement is used to execute a block of code if a certain condition is true and another block of code if the condition is false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Â
For example:
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
if-else if-else statement: The if-else if-else statement is used to test multiple conditions and execute a block of code based on the first true condition.
if (condition1) {
Â
// code to be executed if condition1 is true
Â
} else if (condition2) {
Â
// code to be executed if condition1 is false and condition2 is true
Â
} else {
Â
// code to be executed if both condition1 and condition2 are false
Â
}
For example:
int marks = 75;
Â
if (marks >= 90) {
Â
System.out.println("Grade: A");
Â
} else if (marks >= 75) {
Â
System.out.println("Grade: B");
Â
} else {
Â
System.out.println("Grade: C");
Â
}
switch statement: The switch statement is used to test multiple conditions and execute a block of code based on the matching case value. The switch statement is similar to the if-else if-else statement but is often used when there are many conditions to test. The syntax for the switch statement is:
switch (expression) { case value1: // code to be executed if expression is equal to value1 break; case value2: // code to be executed if expression is equal to value2 break; ... default: // code to be executed if expression is not equal to any of the case values } Â
It's worth noting that the break statement is mandatory in the case block. For example:
char grade = 'B'; switch (grade) { case 'A': System.out.println("Excellent"); break; case 'B': System.out.println("Good"); break; case 'C': System.out.println("Average"); break; default: System.out.println("Invalid Grade"); }
Â
Â
Post a Comment