Control flow statements in Java allow you to control the execution of your code based on certain conditions.
public class ControlFlowExample { public static void main(String[] args) { int age = 20; if (age >= 18) { System.out.println("You are an adult."); } else { System.out.println("You are a minor."); } } }
This program uses an if-else
statement to check if the user is an adult or a minor based on their age.
public class SwitchExample { public static void main(String[] args) { 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"); } } }
This example demonstrates the use of a switch
statement to print the day of the week based on the value of day
.