Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Control Structures in Java: If, If-Else, and Switch

Coding Pirate

Ahoy, mateys! Today we’re embarking on an adventure to explore the treacherous seas of control structures in Java. Grab your compass, and let’s set sail!

If Statements: The Lookout’s Dilemma

Imagine you’re a pirate lookout, scanning the horizon for other ships. If you spot a vessel, you’ll need to raise the alarm. In Java, this decision-making process can be represented by an if statement.

boolean shipSpotted = true;

if (shipSpotted) {
    System.out.println("Arr, there be a ship on the horizon!");
}

In this example, the lookout raises the alarm only when the shipSpotted variable is true. If no ships are spotted, the if statement does nothing, and the crew continues on their merry way.

If-Else Statements: Friend or Foe?

Now, what if you need to determine whether the spotted ship is friend or foe? The if-else statement comes to the rescue! The lookout can hoist the Jolly Roger or prepare for a friendly rendezvous based on the color of the ship’s flag.

boolean blackFlag = true;

if (blackFlag) {
    System.out.println("Yarrr, that be a pirate ship! Hoist the Jolly Roger!");
} else {
    System.out.println("Ahoy, it's a friendly vessel. Prepare to parley!");
}

If the blackFlag variable is true, the lookout identifies the ship as a pirate vessel. Otherwise, they assume it’s a friendly ship.

Switch Statements: Buried Treasure and X Marks the Spot

Picture a treasure map with various symbols representing different types of treasure. A switch statement can be used to identify what each symbol means and guide the crew accordingly.

char treasureSymbol = 'X';

switch (treasureSymbol) {
    case 'X':
        System.out.println("X marks the spot! Start digging, me hearties!");
        break;
    case 'D':
        System.out.println("Arr, we've found a stash of doubloons!");
        break;
    case 'J':
        System.out.println("Yarrr, it's a chest full of jewels!");
        break;
    default:
        System.out.println("Blast, it's just an empty rum bottle...");
}

The switch statement checks the value of treasureSymbol and matches it to one of the case labels. If a match is found, the corresponding block of code is executed. If no match is found, the default block is executed.

And that, me hearties, concludes our voyage through Java control structures. With if, if-else, and switch statements in your programming arsenal, you’re ready to navigate even the stormiest seas of decision-making. Fair winds and following seas!