Control flow statements are essential for controlling the flow of execution in a Java program. They allow you to make decisions, repeat blocks of code, and execute code based on conditions. Let's explore the main control flow statements in Java: `if`, `else`, `switch`, and loops.
1. if Statement
The `if` statement allows you to execute a block of code if a specified condition is true.
if (num > 0) {
System.out.println("The number is positive.");
}
2. if-else Statement
The `if-else` statement allows you to execute one block of code if a condition is true and another block of code if the condition is false.
if (num > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is non-positive.");
}
3. Nested if-else Statement
You can nest `if-else` statements to handle multiple conditions.
if (num > 0) {
System.out.println("The number is positive.");
} else if (num < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
4. switch Statement
The `switch` statement allows you to select one of many code blocks to be executed.
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
// Add cases for other days...
default:
dayName = "Unknown";
}
System.out.println("Today is " + dayName);
5. Loops
Loops are used to execute a block of code repeatedly as long as a specified condition is true.
a. while Loop
The `while` loop executes a block of code as long as the specified condition is true.
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
b. do-while Loop
The `do-while` loop is similar to the `while` loop, but it guarantees that the block of code is executed at least once, even if the condition is false.
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
c. for Loop
The `for` loop is used to iterate over a range of values.
System.out.println("Count: " + i);
}
d. Enhanced for Loop (for-each Loop)
The enhanced `for` loop is used to iterate over elements in an array or a collection.
for (int num : numbers) {
System.out.println("Number: " + num);
}
Conclusion
Control flow statements such as `if`, `else`, `switch`, and loops (`while`, `do-while`, `for`) are essential for writing flexible and efficient Java programs. They allow you to make decisions, handle different cases, and repeat code as needed. Understanding how to use these control flow statements effectively is crucial for becoming proficient in Java programming.
Nenhum comentário:
Postar um comentário