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

Control Structures (if, if-else, switch): Conditional Statements

Header Image

Ahoy there, mateys! Today, we be embarking on an adventure to explore the mysterious land of control structures in Java. Along the way, we’ll be navigating through treacherous seas of conditional statements, including the mighty if, the cunning if-else, and the elusive switch. So hoist the Jolly Roger and join us on this exciting journey as we make landfall on the first island: Conditional Statements.

Conditional Statements

Conditional statements are the compass that guides our Java ship through the stormy seas of decision-making. They be the heart and soul of our control structures, allowing our code to make decisions based on certain conditions.

The Mighty if Statement

Our first weapon in the conditional statements arsenal be the if statement. It allows ye to execute a block of code only if a certain condition be met. If the condition be true, the block of code within the curly braces {} will run, otherwise, it be as if that code never existed. Aye, it be that simple!

Here be an example of the if statement in action. Let’s say ye be counting yer treasure, and ye want to know if ye have more than 100 doubloons:

int doubloons = 150;

if (doubloons > 100) {
    System.out.println("Arr, ye be a wealthy pirate!");
}

In this case, since ye have 150 doubloons, which be more than 100, the condition (doubloons > 100) be true, and the message “Arr, ye be a wealthy pirate!” will be displayed.

The Cunning if-else Statement

But what if ye want to display a different message when ye don’t have more than 100 doubloons? That’s where the if-else statement comes into play. The else part be executed when the condition in the if statement be false. It be like a fork in the road, where yer code can take one path or another.

Here be an example of the if-else statement:

int doubloons = 75;

if (doubloons > 100) {
    System.out.println("Arr, ye be a wealthy pirate!");
} else {
    System.out.println("Yarrr, ye need more doubloons!");
}

In this case, ye only have 75 doubloons, so the condition (doubloons > 100) be false. The code within the else block will execute, and the message “Yarrr, ye need more doubloons!” will be displayed.

The Versatile if-else if-else Statement

Sometimes, ye may need to check for multiple conditions. In such cases, ye can chain together multiple if-else statements using else if. Think of it like a treasure map with multiple paths to follow, depending on the conditions ye encounter.

Take a look at this example, where we check if ye be a wealthy pirate, a modest pirate, or a poor pirate based on the number of doubloons ye have:

int doubloons = 500;

if (doubloons > 1000) {
    System.out.println("Arr, ye be a wealthy pirate!");
} else if (doubloons > 500) {
    System.out.println("Yarrr, ye be a modest pirate!");
} else {
    System.out.println("Blimey, ye be a poor pirate!");
}

In this case, ye have 500 doubloons, so thecondition (doubloons > 1000) be false, and the code moves on to check the next condition (doubloons > 500), which also be false. Finally, the code reaches the else block, and the message “Blimey, ye be a poor pirate!” will be displayed.

As ye can see, the if-else if-else statement allows ye to check multiple conditions and take different actions depending on which condition be true. Remember that as soon as a condition be met, the corresponding block of code will be executed, and the rest of the conditions will not be checked. So, order yer conditions wisely, mateys!

In conclusion, conditional statements be the trusty tools ye need to navigate the treacherous seas of decision-making in Java. With the mighty if, cunning if-else, and versatile if-else if-else statements at yer disposal, ye can take control of yer code and steer it through any challenge ye encounter.

Now that ye have a firm grasp on conditional statements, our next adventure awaits! We’ll be diving into the depths of Boolean expressions and switch statements, uncovering more treasures in the Java seas. So, batten down the hatches and prepare for the next voyage in our Java pirate adventure!

Boolean Expressions

Now that we’ve mastered the art of conditional statements, it be time to take a closer look at the heart of these statements: Boolean expressions. Aye, me hearties, these expressions be the very conditions we check to determine which path our code will take. A Boolean expression be an expression that evaluates to either true or false, and it be the backbone of all our if, if-else, and switch statements.

Comparison Operators

To create Boolean expressions, we use comparison operators. These operators allow us to compare values and check if a certain relationship between them be true. Here be the comparison operators ye need to know:

  • == (Equal to): Checks if two values be equal.
  • != (Not equal to): Checks if two values be not equal.
  • > (Greater than): Checks if one value be greater than another.
  • < (Less than): Checks if one value be less than another.
  • >= (Greater than or equal to): Checks if one value be greater than or equal to another.
  • <= (Less than or equal to): Checks if one value be less than or equal to another.

Let’s take a look at some examples of Boolean expressions using these operators:

int piecesOfEight = 8;
int doubloons = 20;

boolean isEqual = (piecesOfEight == doubloons); // false
boolean isNotEqual = (piecesOfEight != doubloons); // true
boolean isGreater = (doubloons > piecesOfEight); // true
boolean isLess = (piecesOfEight < doubloons); // true
boolean isGreaterOrEqual = (doubloons >= piecesOfEight); // true
boolean isLessOrEqual = (piecesOfEight <= doubloons); // true

Logical Operators

Sometimes, we need to check more than one condition at a time. In these cases, we be using logical operators. These operators help us combine multiple Boolean expressions to create a more complex condition. Here be the logical operators ye need to know:

  • && (Logical AND): Returns true if both Boolean expressions be true.
  • || (Logical OR): Returns true if at least one of the Boolean expressions be true.
  • ! (Logical NOT): Returns the opposite of the Boolean expression.

Let’s take a look at some examples of Boolean expressions using these operators:

boolean hasTreasureMap = true;
boolean hasCompass = false;

// Check if we have both a treasure map and a compass
boolean canFindTreasure = hasTreasureMap && hasCompass; // false

// Check if we have either a treasure map or a compass
boolean canNavigate = hasTreasureMap || hasCompass; // true

// Check if we don't have a compass
boolean needsCompass = !hasCompass; // true

Now ye be well-versed in the art of crafting Boolean expressions, ye can use them to create even more powerful conditional statements in your Java adventures. Just remember, me hearties, that a good pirate always be prepared for any situation, and Boolean expressions be the key to navigating the treacherous waters of decision-making in your code.

Switch Statements

Arr, mateys! We’ve made it through the stormy seas of conditional statements and Boolean expressions. Now, let’s explore the last control structure in our journey: switch statements. Switch statements be an efficient way of handling multiple conditions based on the value of a single variable, savin’ us from writin’ long chains of if-else statements.

Basic Switch Syntax

Here’s the basic syntax of a switch statement:

switch (expression) {
    case value1:
        // Code block for value1
        break;
    case value2:
        // Code block for value2
        break;
    // ...
    default:
        // Code block when no case matches
}
  • The expression must evaluate to a char, byte, short, int, or String (since Java 7).
  • The case keyword marks the start of a new condition.
  • The break keyword terminates the switch statement if a match be found. If ye forget the break, the code will continue executing the next case block (fall-through behavior).
  • The default keyword provides a catch-all for when no cases match.

Let’s see a switch statement in action, as we check the bounty on a pirate’s head:

int pirateBounty = 3;

switch (pirateBounty) {
    case 1:
        System.out.println("A small bounty for a fledgling pirate.");
        break;
    case 2:
        System.out.println("A modest bounty for a seasoned pirate.");
        break;
    case 3:
        System.out.println("A hefty bounty for a notorious pirate!");
        break;
    default:
        System.out.println("No bounty on this pirate's head.");
}

In this example, our pirateBounty be 3, so the output will be “A hefty bounty for a notorious pirate!”.

Enhanced Switch (Since Java 12)

Since Java 12, we’ve had an enhanced switch statement syntax that makes our code even more concise. Here be the new syntax:

switch (expression) {
    case value1 -> {
        // Code block for value1
    }
    case value2 -> {
        // Code block for value2
    }
    // ...
    default -> {
        // Code block when no case matches
    }
}

The enhanced switch statement uses the -> operator instead of the colon (:), and ye don’t need to use the break keyword anymore. Arr, this be a much cleaner way to write switch statements!

Here’s our previous example using the enhanced switch syntax:

int pirateBounty = 3;

switch (pirateBounty) {
    case 1 -> System.out.println("A small bounty for a fledgling pirate.");
    case 2 -> System.out.println("A modest bounty for a seasoned pirate.");
    case 3 -> System.out.println("A hefty bounty for a notorious pirate!");
    default -> System.out.println("No bounty on this pirate's head.");
}

The output will still be “A hefty bounty for a notorious pirate!”.


And there ye have it, me hearties! Ye’ve now learned the essential control structures in Java: if, if-else, and switch statements. Together with Boolean expressions, these structures will help ye navigate through the decision-makin’ waters of your Java code. Remember, a skilled pirate be always ready to adapt and change course, just like your code with these control structures. Fair winds and smooth sailin’ on your Java adventures, mateys!