In Java, control statements are used to control the flow of execution of a program. There are three types of control statements in Java: selection statements, iteration statements, and jump statements.
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
switch statement: This statement allows a program to execute different blocks of code based on the value of a variable. Syntax:
switch (expression) {
case value1:
// code to execute if expression == value1
break;
case value2:
// code to execute if expression == value2
break;
...
default:
// code to execute if none of the cases match
break;
}
for (initialization; condition; update) {
// code to execute repeatedly
}
while loop: This statement executes a block of code as long as a specified condition is true. Syntax:
while (condition) {
// code to execute repeatedly
}
do-while loop: This statement executes a block of code at least once, and then repeats the block as long as a specified condition is true. Syntax:
do {
// code to execute repeatedly
} while (condition);
for-each loop: In Java, a for-each loop (also known as an enhanced for loop) is a convenient way to iterate over elements in a collection or an array. It is especially useful when you want to process all the elements in a collection or array in a sequential order.
for (int number : numbers) {
System.out.println(number);
}
break;
continue statement: This statement is used to skip the current iteration of a loop and move to the next iteration. Syntax:
continue;
return statement: This statement is used to terminate the execution of a method and return a value to the calling method. Syntax:
return value;