DEV Community

Mackenly Jones
Mackenly Jones

Posted on • Originally published at crtv.dev on

Java Decision Structure Basics

Java Decision Structure Basics

Decision structures are sometimes known as control structures. These keywords control the flow of your code by making decisions. These decisions are based on the result of Boolean expressions, which can be constructed using a type of math called Boolean algebra.

Conditionals and loops, the two primary forms of decision structures, are foundational to modern programming. Conditionals function like a decision-making crossroad, steering program execution based on specified conditions. Loops, on the other hand, act like a kid saying, "Are we there yet?" executing a block of code over and over until a specific condition is satisfied.

Conditionals

The most well-known decision structure is if/else if/else. Anytime you need to apply a condition to your code, you will probably use this decision structure. An "if" statement takes a condition. If the condition evaluates to true, the following code will be executed. If an "else if" follows the "if"'s code block, the code following the "else if" will be executed. Finally, if no matches are made to any of the other conditions and an "else" statement is provided, its code will be executed. It's important to remember that the first expression that evaluates to true will be executed, and no other conditions will be tried. If you want to create code where multiple conditions are evaluated independently, you should create multiple if statements.

Java Decision Structure Basics

The next major decision statement is called a switch. This statement takes in a value and compares it to cases. If no cases match, the default case will be executed. This statement is similar to an if but let's you write less code in certain situations.

Java Decision Structure Basics

Loops

Other types of decision structures include while loops, do-while loops, for loops, and foreach loops. These structures execute their code as long as a condition is true. When that condition is false, they stop, and the program continues on.

Java Decision Structure Basics

Summary

With the exception of super basic short scripts, all programs utilize decision structures. A solid grasp of the behavior associated with each structure and when to use which structure is key for any programmer. Without decision structures, we would be stuck with only linear programming. Such an approach lacks the adaptability necessary to address the complexity of real-world applications.

Top comments (0)