Control statements in Java manage the flow of execution, enabling decision-making and repetition. The if
, else
, and switch
statements allow conditional execution, while loops like for
, while
, and do-while
enable repeated execution of code. These statements are essential for controlling program behavior based on conditions or iteration.
if
, if-else
, if-else if-else
, switch
for
, while
, do-while
break
, continue
, return
if
: Executes a block of code if the condition is true.
if (condition) { // code to execute }
if-else
: Executes one block of code if the condition is true, and another if false.
if (condition) { // code for true
} else { // code for false }
if-else if-else
: Allows multiple conditions to be tested sequentially.
if (condition1) {
// code for condition1
} else if (condition2) {
// code for condition2
} else {
// code if no conditions are true }
switch
: Compares a variable to multiple possible values and executes the corresponding block.
switch (variable) {
case value1: // code for value1
break;
case value2:
// code for value2
break;
default:
// default code
}
for
: Executes a block of code for a specific number of iterations.
for (int i = 0; i < 5; i++) {
// code to execute
}
while
: Repeats a block of code as long as the condition is true (condition checked before execution).
while (condition) {
// code to execute
}
do-while
: Similar to while
, but checks the condition after execution (ensures at least one execution).
do { // code to execute
} while (condition);
break
: Exits the current loop or switch
statement.
for (int i = 0; i < 5; i++) {
if (i == 3) {
break; // exits the loop when i is 3
}
}
continue
: Skips the current iteration of a loop and moves to the next iteration
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // skips when i is 3
}
System.out.println(i);
}
return
: Exits from the current method and optionally returns a value.
int sum(int a, int b) {
return a + b;
// exits the method and returns the result
}