Control statements in Java are constructs that allow you to dictate the flow of execution in your program. These include conditional statements, loop statements, and branching statements.
1. Conditional Statements
Conditional statements allow you to execute specific blocks of code based on certain conditions.
If Statement
The if
statement evaluates a boolean expression and executes the associated block of code if the expression evaluates to true.
if (condition) {
// code to be executed if condition is true
}
If-Else Statement
The if-else
statement provides an alternative block of code that executes if the condition is false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
If-Else-If Ladder
The if-else-if
ladder allows you to check multiple conditions sequentially.
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
Switch Statement
The switch
statement allows you to select one of many code blocks to be executed.
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases...
default:
// code to be executed if expression doesn't match any case
}
2. Loop Statements
Loop statements allow you to execute a block of code multiple times.
For Loop
The for
loop is used to iterate over a range of values.
for (initialization; condition; update) {
// code to be executed for each iteration
}
// Example
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
While Loop
The while
loop executes a block of code as long as a specified condition is true.
while (condition) {
// code to be executed as long as condition is true
}
// Example
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
Do-While Loop
The do-while
loop is similar to the while
loop, but it guarantees that the block of code is executed at least once.
do {
// code to be executed
} while (condition);
// Example
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 10);
3. Branching Statements
Branching statements allow you to change the flow of execution based on certain conditions.
Break Statement
The break
statement is used to exit from a loop or a switch statement prematurely.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exits the loop when i is 5
}
System.out.println(i);
}
Continue Statement
The continue
statement is used to skip the current iteration of a loop and proceed with the next iteration.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // skips the rest of the loop for even numbers
}
System.out.println(i);
}
Return Statement
The return
statement is used to exit from a method and optionally return a value.
public int add(int a, int b) {
return a + b; // returns the sum of a and b
}