Control Statements in Java
In Java, control statements are used to control the flow of execution in a program. They allow you to make decisions, iterate over collections, and perform other types of control over your code. There are three main types of control statements in Java: selection statements, iteration statements, and jump statements.
Selection Statements:
if statement: Used to execute a block of code only if a specified condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
if-else statement: Used to execute one block of code if the condition is true and another block of code if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
if-else-if ladder: Used to test multiple conditions.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if condition2 is true
} else {
// block of code to be executed if neither condition1 nor condition2 is true
}
switch statement: Used to select one of many code blocks to be executed.
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code block
}
Iteration Statements:
for loop: Used to repeat a block of code a known number of times.
for (initialization; condition; update) {
// block of code to be executed
}
while loop: Repeats a block of code as long as a specified condition is true.
while (condition) {
// block of code to be executed
}
do-while loop: Similar to a while loop, but the block of code is executed at least once before the condition is tested.
do {
// block of code to be executed
} while (condition);
Jump Statements:
break statement: Used to terminate a loop or switch statement.
break;
continue statement: Skips the current iteration of a loop.
continue;
return statement: Exits a method and optionally returns a value.
return value;
These control statements are essential for writing efficient and structured Java programs.