Java Control Statements are statements that allow you to control the flow of execution in a Java program. They include conditional statements, loop statements, and branching statements.
1. Conditional Statements:Conditional statements allow you to execute different sets of code depending on whether a certain condition is true or false. There are two types of conditional statements in Java: if-else and switch statements.
* if-else statements: These statements allow you to execute one block of code if a condition is true, and another block of code if the condition is false. Here's an example:
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is less than or equal to 5");
}
* switch statements: These statements allow you to execute different blocks of code based on the value of an expression. Here's an example:
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
// and so on...
default:
System.out.println("Invalid day");
break;
}
2. Loop Statements:
Loop statements allow you to repeat a block of code until a certain condition is met. There are three types of loop statements in Java: for, while, and do-while loops.
* for loop: The for loop allows you to execute a block of code for a fixed number of times. Here's an example:
for (int i = 0; i < 10; i++) {
System.out.println("The value of i is: " + i);
}
* while loop: The while loop allows you to execute a block of code while a certain condition is true. Here's an example:
while (x < 10) {
System.out.println("The value of x is: " + x);
x++;
}
* do-while loop: The do-while loop is similar to the while loop, except that it executes the block of code at least once, even if the condition is false. Here's an example:
do {
System.out.println("The value of x is: " + x);
x++;
} while (x < 10);
3. Branching Statements:
Branching statements allow you to change the flow of execution in your program. There are two types of branching statements in Java: break and continue statements.
* break statement: The break statement allows you to exit a loop or switch statement. Here's an example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println("The value of i is: " + i);
}
* continue statement: The continue statement allows you to skip the current iteration of a loop and move on to the next iteration. Here's an example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
System.out.println("The value of i is: " + i);
}
Control statements are an essential aspect of programming that allows you to create complex logic in your programs. By using control statements in Java, you can create more sophisticated programs that can handle different scenarios and input data.