Decision control in Java
Decision control in Java are constructs that allow the program to choose different paths of execution based on conditions. These structures enable the program to make decisions and perform different actions based on various criteria. The primary decision control structures in Java are:
- if statement
- if-else statement
- if-else-if ladder
- switch statement
if statement
The if
statement evaluates a condition and executes a block of code if the condition is true.
if (condition) {
// code to be executed if condition is true
}
Example:
int a = 10;
if (a > 5) {
System.out.println("a is greater than 5");
}
if-else statement
The if-else
statement allows you to execute one block of code if the condition is true and another block if the condition is false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example:
int a = 10;
if (a > 5) {
System.out.println("a is greater than 5");
} else {
System.out.println("a is not greater than 5");
}
if-else-if ladder
The if-else-if
ladder is used to test multiple conditions. It is a chain of if-else statements.
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 all conditions are false
}
Example:
int a = 10;
if (a > 15) {
System.out.println("a is greater than 15");
} else if (a > 5) {
System.out.println("a is greater than 5 but less than or equal to 15");
} else {
System.out.println("a is 5 or less");
}
switch statement
The switch
statement allows you to execute one block of code among many alternatives based on the value of an expression.
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
// you can have any number of case statements
default:
// code to be executed if expression doesn't match any case
}
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;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
Summary
Decision control in Java are essential for making choices and executing different blocks of code based on conditions. The if
, if-else
, if-else-if ladder
, and switch
statements provide a way to handle different scenarios and execute the appropriate code accordingly.