Control Statements in Java: if-else, switch, and Loops Explained
Diagram of Control Statements in Java: if-else.
Control Statements in Java
Control statements allow you to control the flow of execution in a Java program. They include conditional statements like if-else and switch, as well as looping structures like for, while, and do-while.
Let’s explore how they work with examples.
The if-else statement is used to execute code blocks based on conditions.
if (condition) {
// code if true
} else {
// code if false
}
int number = 10;
if (number > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}
Used for checking multiple conditions.
int marks = 85;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
The switch statement is an alternative to multiple if-else conditions.
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other Day");
}
Loops execute a block of code multiple times.
Used when the number of iterations is known.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Used when the condition is checked before executing the loop.
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Executes the block at least once before checking the condition.
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
Use if-else for complex conditions
Use switch for multiple fixed values
Use for when you know how many times to loop
Use while or do-while when the number of iterations is not known in advance
Control statements are essential for building logic in Java programs. With if-else, switch, and loops, you can handle decision-making and repetitive tasks efficiently.
Practice these examples to gain confidence and build more dynamic Java applications.