1. java
  2. /basics
  3. /conditionals

Conditional Statements in Java

Introduction

Conditionals emerge as a vital aspect of any given programming language. The same goes for Java. These control flow elements allow us to execute specific statements based on the truth or falsity of a given condition. As you might expect, the data types used in your program play a crucial role, with boolean expressions — evaluating to either true or false — frequently working alongside conditionals in your code.

Java's conditional statements are versatile and compatible with several data types, including numerical, string, and boolean types. To evaluate and incorporate them properly, the language provides a variety of operators we can turn to.

We'll examine four distinct types of conditional statements, and briefly explain a shorthand approach for some of them.

Curious about boolean data types? Take a look at our detailed explanation on booleans

If Statements

First off, we have the if statement as the cornerstone of conditional statements. It empowers us to execute a block of code if a specific condition is true. So, to determine whether the execution happens, the condition relies on a boolean expression in combination with operators. Let's take a closer look at the basic syntax.

if (condition) {
  // code to execute if condition is true
}

Suppose we have a variable that contains an integer value. We want to execute some code that checks the person's age and outputs a specific print statement based on the condition.

int age = 20;

if (age >= 18) {
  System.out.println("You are an adult.");
}
// Output: You are an adult.

As we can see, the code block is executed because the value of age meets the condition of being greater than or equal to 18.

If-Else Statements

Moving on, we have the more versatile if-else statement. With it, we can execute one block of code if a condition is true and another block if the condition is false. Logically, the syntax is extended, but pretty straightforward.

if (condition) {
  // code to execute if condition is true
} else {
  // code to execute if condition is false
}

In a similar manner from before, imagine we have a variable containing a numerical value that represents the temperature in Celsius. We want to print "It's hot!" if the temperature is greater than or equal to 30, and "It's cold!" if otherwise.

int temperature = 25;

if (temperature >= 30) {
  System.out.println("It's hot!");
} else {
  System.out.println("It's cold!");
}
// Output: It's cold!

In this specific case, we'll see the code block within the else statement executed, because the value of the temperature variable doesn't satisfy the condition of being greater than or equal to 30.

Else-If Statements

When a single if or if-else statement isn't enough, we can turn to the else-if statement. With this neat construct, we can execute a block of code if the initial condition is false, but another condition is true.

if (condition1) {
  // code to execute if condition1 is true
} else if (condition2) {
  // code to execute if condition2 is true
} else {
  // code to execute if neither condition1 nor condition2 is true
}

To showcase the multiple case structure, we can introduce an interesting example. We'll create a variable that stores a letter grade (A through F). The goal is to print a message based on the grade's value.

String grade = "B";

if (grade.equals("A")) {
  System.out.println("Excellent!");
} else if (grade.equals("B")) {
  System.out.println("Good job!");
} else if (grade.equals("C")) {
  System.out.println("You can do better.");
} else {
  System.out.println("Try harder next time.");
}
// Output: Good job!

Since the value of the grade is "B", the code in the second block is executed, and the corresponding message is displayed as seen in the output comment.

Switch Statements

Switch statements offer another approach to nested structures. They're most useful when we're dealing with a limited number of possible values for a variable. The switch statement evaluates the variable's value and executes the code block that corresponds to that specific value, simplifying our conditional logic.

switch (variable) {
  case value1:
    // code to execute if variable equals value1
    break;
  case value2:
    // code to execute if variable equals value2
    break;
  // more cases can be added here
  default:
    // code to execute if none of the cases match variable
    break;
}

We can observe the syntax that begins with the keyword switch, followed by parentheses enclosing the variable to be evaluated. Then, the code block contains a series of cases, each representing a possible value of the variable. If the variable's value matches one of the cases, the corresponding code block is executed.

You'll also notice the break keyword. We use it to exit the switch statement once a matching case is found and executed. If it's omitted, the program continues executing the code in the following cases, even if they don't match the variable's value.

Finally, if none of the cases match the variable's value, the code in the default block is executed. While the default block is optional, it's considered good practice to include it to handle unexpected variable values.

String dayOfWeek = "Wednesday";

switch (dayOfWeek) {
  case "Monday":
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
  case "Friday":
    System.out.println("It's a weekday.");
    break;
  case "Saturday":
  case "Sunday":
    System.out.println("It's the weekend!");
    break;
  default:
    System.out.println("Invalid day.");
    break;
}
// Output: It's a weekday.

In our showcase example, the value of dayOfWeek is "Wednesday", so the code in the first block is executed.

The Ternary Operator

We can leverage the ternary operator as a more elegant and concise way to express conditional statements. It's particularly handy as an alternative to if-else statements, specifically when we need to assign a value to a variable based on a specific condition.

Furthermore, the ternary operator works with three operands: a boolean expression, a value to return if the expression evaluates to true, and another value to return if the expression evaluates to false.

variable = (condition) ? value1 : value2;

If the condition is true, the value of the variable is set to the first value. Otherwise, the value of the variable is set to the second one.

Once again, we'll turn to an example of two variables that hold integer values. We'll want to determine the maximum value of the two variables and assign it to a new variable called max.

int num1 = 10;
int num2 = 20;
int max = (num1 > num2) ? num1 : num2;
// Output: max = 20

Logically, the boolean expression (num1 > num2) evaluates to false because 10 is not greater than 20. Therefore, the value of max is set to the value of num2, which is 20.

While the ternary operator is a powerful shorthand syntax, it's best to use it wisely and only when it enhances your code's readability. Excessive use of the ternary operator can lead to code that is challenging to read and maintain.

Summary

Throughout this overview, we've explored various types of conditionals in Java and demonstrated how to utilize them at a basic level. We've discussed the four distinct statements alongside the ternary operator and a few caveats surrounding each approach.

To continue developing your Java skillset, remember to refer to the useful resources provided below.

Useful Resources

The Basics of Java Syntax

Java Data Types - A Beginner's Guide

The Java Variables Essentials

Overview of Operators in Java

The Basics of Java Loops

An Introduction to Java Output