In Java, you can use control flow statements to alter the sequential execution of your code based on certain conditions. The main control flow statements in Java are if-else statements, switch statements, and loops (such as for, while, and do-while). Let’s take a look at each of these statements and their usage:
if (condition) { // code to execute if the condition is true } else { // code to execute if the condition is false }
Example:
int x = 5; if (x > 0) { System.out.println("x is positive"); } else { System.out.println("x is non-positive"); }
switch (variable) { case value1: // code to execute if variable equals value1 break; case value2: // code to execute if variable equals value2 break; // more cases... default: // code to execute if none of the cases match }
Example
int day = 3; String dayName; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; // more cases... default: dayName = "Invalid day"; } System.out.println("The day is: " + dayName);
for (initialization; condition; update) { // code to be executed }
Example:
for (int i = 1; i <= 5; i++) { System.out.println(i); }
while (condition) { // code to be executed }
Example:
int i = 1; while (i <= 5) { System.out.println(i); i++; }
do { // code to be executed } while (condition);
Example:
int i = 1; do { System.out.println(i); i++; } while (i <= 5);
These are the basic control flow statements in Java. They provide you with the flexibility to make decisions and repeat code execution based on different conditions.
Copyright ©TechOceanhub All Rights Reserved.