Decision-Making statements are used to make decisions based on certain conditions. The following are the decision-making statements.
If-Else Statements
If the condition specified in the if block is true, then the logic inside the if block will be executed, otherwise it enters the else block and executes the logic in it
if(condition) {
// This code executes if the condition is true
} else {
// This code executes if the condition is false
}
Example:
int x = 5;
if(x > 0) {
System.out.println("x is positive");
} else {
System.out.println("x is non-positive");
}
Here, the output will be “x is positive”, since the value of x is 5 and the condition in the if block is true.
If-Else-If Statements
In if -else we do not mention the condition in the else block, so if one wants to check against multiple conditions, use if-else-if statements.
Syntax:
if(condition1) {
/ this code executes if condition1 is true
} else if(condition2) {
/ this code executes if condition1 is false and condition2 is true
} else if(condition3) {
/ this code executes if condition1 and condition2 are false and condition3 is true } ...
else {
/ this code executes if all conditions are false
}
Example:
int y = 10;
if(y > 0) {
System.out.println("y is positive");
} else if(y < 0) {
System.out.println("y is negative");
} else {
System.out.println("y is zero");
}
Switch case:
A switch-case statement is used to execute a block of code based on the value of a variable.
Syntax:
switch(variable) {
case value1:
/ code to be executed if the variable is equal to value1
break;
case value2:
/ this code executes if the variable is equal to value2
break;
...
default:
/ this code executes if the variable does not match any of the values
}
Example:
int day = 3;
switch(day) {
case 1:
System. out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
...
default:
System.out.println("Invalid day");
}
This switch-case statement will print "Wednesday" to the console