Control Structures in Java - Explained
1. Introduction to Control Structures
Control structures in Java define the flow of execution in a program. They allow you to control the order in
which statements are executed, based on conditions or repetition. Java supports the following control
structures:
- Sequential
- Selection (Decision Making)
- Iteration (Loops)
- Jump Statements
2. Sequential Control Structure
This is the simplest control structure where instructions are executed one after another from top to bottom.
No conditions or loops are involved.
Example:
int a = 5;
int b = 10;
int sum = a + b;
System.out.println(sum);
3. Selection (Decision-Making) Statements
These statements let the program make decisions based on conditions.
a. if Statement:
Executes a block if the condition is true.
Example:
if (age >= 18) {
System.out.println("You can vote.");
b. if-else Statement:
Executes one block if true, another if false.
Example:
if (marks >= 33) {
System.out.println("Pass");
} else {
System.out.println("Fail");
c. if-else-if Ladder:
Allows multiple conditions.
Example:
if (score >= 90) {
System.out.println("A Grade");
} else if (score >= 75) {
System.out.println("B Grade");
} else {
System.out.println("Needs Improvement");
d. switch Statement:
Efficient for multiple constant comparisons.
Example:
switch(day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Other day");
4. Iteration (Looping) Statements
Loops help in executing a block of code multiple times.
a. for Loop:
Best when the number of iterations is known.
Example:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
b. while Loop:
Executes block repeatedly as long as the condition is true.
Example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
c. do-while Loop:
Executes the block at least once.
Example:
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
5. Jump Statements
Used to alter the normal flow of control in loops or methods.
a. break:
Exits the loop or switch prematurely.
Example:
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
System.out.println(i);
b. continue:
Skips current iteration and continues with the next.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
c. return:
Exits from the method.
Example:
public void greet() {
System.out.println("Hello");
return;