Search⌘ K
AI Features

Control Flow: Conditional and Iterative Statements

Explore modern control flow in Java with conditional and iterative statements. Understand advanced switch expressions, pattern matching, and efficient loop constructs. Learn to write cleaner, more readable code that avoids common performance pitfalls like inefficient LinkedList traversal.

We'll cover the following...

While basic if statements and for loops are the first constructs we learn in programming, modern Java has significantly evolved how we control the flow of our applications. Interviewers frequently test your knowledge of recent language additions, such as pattern matching, as well as your understanding of how iterative statements interact with Java's underlying data structures.

Let's explore the modern mechanics of conditional and iterative statements in Java.

AI Powered
Saved
10 attempts left
Reset
Question

What are the advantages of modern switch expressions over the legacy switch statement?

You have 10 attempts to answer.

To see the modern syntax in action, consider the following method, which calculates a discount based on a membership tier.

Java
public class Demonstration {
public static void main(String[] args) {
Demonstration demo = new Demonstration();
System.out.println("GOLD: " + demo.calculateDiscount("GOLD"));
System.out.println("PLATINUM: " + demo.calculateDiscount("PLATINUM"));
System.out.println("SILVER: " + demo.calculateDiscount("SILVER"));
System.out.println("BRONZE: " + demo.calculateDiscount("BRONZE"));
System.out.println("REGULAR: " + demo.calculateDiscount("REGULAR"));
}
public double calculateDiscount(String membership) {
return switch (membership) {
case "GOLD", "PLATINUM" -> 0.20;
case "SILVER" -> 0.10;
case "BRONZE" -> 0.05;
default -> 0.0;
};
}
}
    ...