Control Statements
In Java, control statements are used to control the flow of a program. They allow you to make decisions, repeat actions, and perform various operations based on certain conditions. There are three main categories of control statements in Java:
Selection Statements: These are used for making decisions in your code.
ifstatementif-elsestatementswitchstatement
Iteration Statements: These are used for repeating a set of statements.
forloopwhileloopdo-whileloop
Jump Statements: These are used for transferring control within your code.
breakstatementcontinuestatementreturnstatement
Selection Statements
if statement
if statementThe if statement allows you to execute a block of code if a given condition is true.
int age = 20;
if (age >= 18) {
System.out.println("You are an adult.");
}if-else statement
if-else statementThe if-else statement allows you to execute one block of code if a condition is true and another block if the condition is false.
int number = 7;
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}switch statement
switch statementThe switch statement allows you to select one of many code blocks to be executed.
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// ... (cases for other days)
default:
System.out.println("Invalid day");
}Iteration Statements
for loop
for loopThe for loop is used to iterate a specific number of times.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}while loop
while loopThe while loop is used when you don't know in advance how many times the loop will run.
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}do-while loop
do-while loopThe do-while loop is similar to the while loop but guarantees that the loop block is executed at least once.
int x = 1;
do {
System.out.println("Value of x: " + x);
x++;
} while (x <= 3);Jump Statements
break statement
break statementThe break statement is used to exit a loop or switch statement.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
System.out.println("Value of i: " + i);
}continue statement
continue statementThe continue statement is used to skip the current iteration of a loop and continue with the next iteration.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip iteration when i is 3
}
System.out.println("Value of i: " + i);
}return statement
return statementThe return statement is used to exit a method and return a value to the caller.
public int add(int a, int b) {
int sum = a + b;
return sum;
}These control statements are fundamental in Java programming and are essential for controlling the flow of your code and making your programs more flexible and responsive to different conditions.
Last updated
Was this helpful?