Java Basics - Part 2: Control Flow
Control Flow
If-Else Statements
// Simple if statement
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
}
// If-else statement
if (score >= 90) {
System.out.println("Grade: A");
} else {
System.out.println("Grade: B or lower");
}
// If-else if-else chain
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 if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
// Nested if statements
if (score >= 60) {
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 80) {
System.out.println("Good!");
} else {
System.out.println("Passing");
}
} else {
System.out.println("Failing");
}
1
Switch Statement
// Basic switch statement
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;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
}
// Switch with String (Java 7+)
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("Red fruit");
break;
case "banana":
System.out.println("Yellow fruit");
break;
case "orange":
System.out.println("Orange fruit");
break;
default:
System.out.println("Unknown fruit");
}
// Switch expression (Java 14+)
String result = switch (day) {
2
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
// Switch with yield (Java 14+)
String result2 = switch (day) {
case 1, 2, 3, 4, 5 -> {
yield "Weekday";
}
case 6, 7 -> {
yield "Weekend";
}
default -> {
yield "Invalid";
}
};
Loops
For Loop
// Basic for loop
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
// For loop with multiple variables
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i: " + i + ", j: " + j);
}
// Enhanced for loop (for arrays/collections)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
// Enhanced for loop with collections
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
System.out.println("Hello, " + name);
}
// Nested for loops
for (int i = 1; i <= 3; i++) {
3
for (int j = 1; j <= 3; j++) {
System.out.println("i=" + i + ", j=" + j);
}
}
While Loop
// Basic while loop
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
// While loop with condition
int number = 10;
while (number > 0) {
System.out.println(number);
number /= 2;
}
// While loop with break
int i = 0;
while (true) {
if (i >= 5) {
break;
}
System.out.println(i);
i++;
}
Do-While Loop
// Basic do-while loop
int i = 0;
do {
System.out.println("Count: " + i);
i++;
} while (i < 5);
// Do-while with condition
int number = 1;
do {
System.out.println(number);
number *= 2;
} while (number < 10);
4
Break and Continue
// Break example
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit loop when i equals 5
}
System.out.println(i);
}
// Continue example
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
// Break with labels
outerLoop: for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
break outerLoop; // Break out of both loops
}
System.out.println("i=" + i + ", j=" + j);
}
}
// Continue with labels
outerLoop: for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
continue outerLoop; // Skip to next iteration of outer loop
}
System.out.println("i=" + i + ", j=" + j);
}
}
Conditional Operator (Ternary)
// Basic ternary operator
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
// Nested ternary operator
int score = 85;
5
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" :
(score >= 60) ? "D" : "F";
// Ternary with method calls
int a = 5, b = 10;
int max = (a > b) ? a : b;
int min = (a < b) ? a : b;
// Ternary with different types
Object result = (score >= 60) ? "Pass" : 0;
Pattern Matching (Java 17+)
// Pattern matching with instanceof
Object obj = "Hello";
if (obj instanceof String str) {
System.out.println("String length: " + str.length());
}
// Pattern matching in switch (Java 17+)
Object value = "Hello";
String result = switch (value) {
case String s -> "String: " + s;
case Integer i -> "Integer: " + i;
case null -> "null";
default -> "Unknown";
};
// Pattern matching with guards
Object obj2 = "Hello";
if (obj2 instanceof String str && str.length() > 3) {
System.out.println("Long string: " + str);
}
Quick Reference
Control Flow Summary
• if-else: Conditional execution
• switch: Multi-way branching
• for: Counted loops
• while: Pre-test loops
• do-while: Post-test loops
6
• break: Exit loop or switch
• continue: Skip to next iteration
• ternary: Conditional expression
Loop Comparison
Loop Type When to Use Example
for Known number of iterations for (int i = 0;
i < n; i++)
while Unknown iterations, pre-test while
(condition)
do-while Unknown iterations, do { } while
post-test (condition)
enhanced for Iterating over collections for (Type item :
collection)
Best Practices
1. Use meaningful variable names in loops
2. Avoid infinite loops
3. Use break and continue sparingly
4. Prefer enhanced for loops for collections
5. Use switch for multiple conditions
6. Keep loop bodies small and focused
7. Use appropriate loop type for the task
8. Avoid deeply nested loops when possible
9. Use ternary operator for simple conditionals
10. Consider pattern matching for type checking