Learn about Java Control Statements to control the flow of your program using decision-making and loops with practical examples.
Control statements in Java allow you to control the flow of program execution. Using them, you can execute statements conditionally or repeatedly based on certain conditions.
The if-else statement is used to execute a block of code based on a condition. If the condition is true, the code inside 'if' executes; otherwise, 'else' block executes.
int num = 10;
if (num % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
The switch statement allows a variable to be tested for equality against a list of values.
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("Other day");
}
The for loop executes a block of code for a fixed number of times.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
The while loop executes a block of code as long as the condition is true.
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
The do-while loop executes the block of code once before checking the condition and then continues if the condition is true.
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
The break statement exits a loop immediately, while continue skips the current iteration and moves to the next.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
if (i == 5) break;
System.out.println(i);
}
// Output: 1 2 4