Control statements in Java are used to control the flow of execution in a program. They allow you to conditionally execute code blocks, loop over code blocks, and alter the flow of execution based on conditions.
The if-else statement is used to execute a block of code if a condition is true, and another block of code if the condition is false.
int number = 10;
if (number > 0) {
System.out.println("Number is positive");
} else {
System.out.println("Number is non-positive");
}The switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the code block corresponding to the matching case is executed.
int day = 3;
String dayString;
switch (day) {
case 1:
dayString = "Monday";
break;
case 2:
dayString = "Tuesday";
break;
// Add more cases as needed
default:
dayString = "Invalid day";
}
System.out.println(dayString);
The for loop is used to iterate a block of code a fixed number of times.
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}The while loop is used to iterate a block of code as long as a condition is true.
int i = 0;
while (i < 5) {
System.out.println("Iteration: " + i);
i++;
}