You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Control flow statements determine the order in which instructions are executed. Java provides conditionals (if, switch) and loops (for, while, do-while) to make programs dynamic and responsive.
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
| Operator | Meaning | Example |
|---|---|---|
&& | AND | a > 0 && b > 0 |
|| | OR | a > 0 || b > 0 |
! | NOT | !finished |
A concise alternative to simple if/else:
String result = (score >= 60) ? "Pass" : "Fail";
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("Other day");
}
No break needed — uses arrow syntax:
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid";
};
Tip: The enhanced switch is both an expression (returns a value) and eliminates fall-through bugs caused by missing
breakstatements.
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
Used to iterate over arrays and collections:
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
Repeats while a condition is true:
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
Executes the body at least once, then checks the condition:
int num = 0;
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.