Control Flow Statements in Java (if, switch, loops)
Control flow statements in Java allow a program to make decisions, repeat tasks, and execute code conditionally. Mastering these concepts is essential for building logical and dynamic applications. In this blog, we’ll cover three core types of control flow statements: if-else, switch, and loops.
🔹 1. if-else Statement
The if statement is used to execute a block of code if a specified condition is true. The optional else or else if blocks handle other outcomes.
Syntax:
int age = 18;
if (age >= 18) {
System.out.println("Eligible to vote");
} else {
System.out.println("Not eligible to vote");
}
You can also chain multiple conditions using else if.
🔹 2. switch Statement
The switch statement is used when you have multiple conditions to check against a single value. It’s often cleaner than writing many if-else statements.
Syntax:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
The break statement prevents fall-through. The default block handles unmatched cases.
🔹 3. Loops in Java
Loops allow you to execute a block of code repeatedly.
➤ for Loop
Used when the number of iterations is known
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
➤ while Loop
Executes the block as long as the condition is true.
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
➤ do-while Loop
Similar to while, but guarantees at least one execution.
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
✅ Conclusion
Control flow statements are the decision-making backbone of Java programming. The if-else and switch statements control what code runs based on conditions, while loops (for, while, do-while) handle repetition. By understanding and practicing these structures, you’ll be ready to write more dynamic and efficient programs in Java.
Keep experimenting — logic is the heart of programming!
Learn Full Stack Java Training
Introduction to Java and Full Stack Development
Setting Up Java Development Environment (JDK, IntelliJ, Eclipse)
Java Basics: Variables, Data Types, and Operators
Visit Our Quality Thought Training Institute
Comments
Post a Comment