Control Structures in Java

1. Overview

In the most basic sense, a program is a list of instructions. Control structures are programming blocks that can change the path we take through those instructions.

In this tutorial, we’ll explore control structures in Java.

There are three kinds of control structures:

  • Conditional Branches, which we use for choosing between two or more paths. There are three types in Java: if/else/else ifternary operator and switch.
  • Loops that are used to iterate through multiple values/objects and repeatedly run specific code blocks. The basic loop types in Java are forwhile and do while.
  • Branching Statements, which are used to alter the flow of control in loops. There are two types in Java: break and continue.

2. If/Else/Else If

The if/else statement is the most basic of control structures, but can also be considered the very basis of decision making in programming.

While if can be used by itself, the most common use-scenario is choosing between two paths with if/else:

if (count > 2) {
    System.out.println("Count is higher than 2");
} else {
    System.out.println("Count is lower or equal than 2");
}

Theoretically, we can infinitely chain or nest if/else blocks but this will hurt code readability, and that’s why it’s not advised.

We’ll explore alternative statements in the rest of this article.

3. Ternary Operator

We can use a ternary operator as a shorthand expression that works like an if/else statement.

Let’s see our if/else example again:

if (count > 2) {
    System.out.println("Count is higher than 2");
} else {
    System.out.println("Count is lower or equal than 2");
}

We can refactor this with a ternary as follows:

System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or equal than 2");

While ternary can be a great way to make our code more readable, it isn’t always a good substitute for if/else.

4. Switch

If we have multiple cases to choose from, we can use a switch statement.

Let’s again see a simple example:

int count = 3;
switch (count) {
case 0:
    System.out.println("Count is equal to 0");
    break;
case 1:
    System.out.println("Count is equal to 1");
    break;
default:
    System.out.println("Count is either negative, or higher than 1");
    break;
}

Three or more if/else statements can be hard to read. As one of the possible workarounds, we can use switch, as seen above.

And also keep in mind that switch has scope and input limitations that we need to remember before using it.

5. Loops

We use loops when we need to repeat the same code multiple times in succession.

Let’s see a quick example of comparable for and while type of loops:

for (int i = 1; i <= 50; i++) {
    methodToRepeat();
}

int whileCounter = 1;
while (whileCounter <= 50) {
    methodToRepeat();
    whileCounter++;
}

Both code blocks above will call methodToRepeat 50 times.

6. Break

We need to use break to exit early from a loop.

Let’s see a quick example:

List<String> names = getNameList();
String name = "John Doe";
int index = 0;
for ( ; index < names.length; index++) {
    if (names[index].equals(name)) {
        break;
    }
}

Here, we are looking for a name in a list of names, and we want to stop looking once we’ve found it.

A loop would normally go to completion, but we’ve used break here to short-circuit that and exit early.

7. Continue

Simply put, continue means to skip the rest of the loop we’re in:

List<String> names = getNameList();
String name = "John Doe";
String list = "";
for (int i = 0; i < names.length; i++) { 
    if (names[i].equals(name)) {
        continue;
    }
    list += names[i];
}

Here, we skip appending the duplicate names into the list.

As we’ve seen here, break and continue can be handy when iterating, though they can often be rewritten with return statements or other logic.

8. Conclusion

In this quick article, we learned what control structures are and how to use them to manage flow control in our Java programs.

All code presented in this article is available over on GitHub.

Related posts:

Java Program to Implement Range Tree
Working with Kotlin and JPA
Java Program to Implement the Vigenere Cypher
Phương thức tham chiếu trong Java 8 – Method References
Java Program to Implement Control Table
How to Set TLS Version in Apache HttpClient
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
The Dining Philosophers Problem in Java
Java Program to Perform Finite State Automaton based Search
Java Program to Implement Max-Flow Min-Cut Theorem
ClassNotFoundException vs NoClassDefFoundError
Using JWT with Spring Security OAuth (legacy stack)
Spring Boot - Tomcat Deployment
How to Read HTTP Headers in Spring REST Controllers
Chuyển đổi giữa các kiểu dữ liệu trong Java
Encode/Decode to/from Base64
Concrete Class in Java
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Consumer trong Java 8
Apache Commons Collections BidiMap
Java Program to Implement Solovay Strassen Primality Test Algorithm
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions
Programmatic Transaction Management in Spring
Introduction to Project Reactor Bus
Rate Limiting in Spring Cloud Netflix Zuul
Java Program to Implement Meldable Heap
Java Program to Check whether Undirected Graph is Connected using DFS
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Spring Boot - OAuth2 with JWT
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)