A Java Approach: Selection Structures - Use Cases

Hello everyone and welcome back! Up to now we have been concerned to make as complete an overview as possible of the fundamental concepts we need to approach the use of conditional structures. We have therefore introduced the concept of conditional structures, outlining the various situations that could arise. We then went on to outline the main features of Boolean algebra, analysing the use of Boolean variables and Boolean operators.

One concept that is worth repeating is that conditional structures, also called flow control structures, serve to modify the normal flow of program execution. 

Since learning to program is not enough to read, let's go and analyse some practical examples so that we can see in action the concepts we have analysed so far. It must be said that, in examining some examples, I will take for granted the theoretical and practical aspects concerning the variables, focusing on the aspects concerning the selection structures.

Case 1: Nested selection structures

A first question that could be asked is the case of the nested selection structures. One might wonder whether a second if can be grafted within an if. 

The answer is yes.

Let's see how.

// check that n1 is greater than or equal to n2
if (n1 >= n2) {
    // check that n1 is greater than or equal to n3
    if (n1 >= n3) {
        largest = n1;
    else {
        largest = n3;
} else {
// check that n2 is greater than or equal to n3
    if (n2 >= n3) {
        largest = n2;
    else {
        largest = n3;
System.out.println("Largest Number: " + largest);

This example may seem complex on the surface, but if we read it carefully, we realize that the task it performs is quite simple: it is concerned with finding the variable that has the maximum value within a set of three variables. 

To do this, the reasoning is as follows: to be the maximum, one value must be greater than the other two. So what happens is that you check if n1 is greater than n2. If this is true, then you check that n1 is also greater than n3. If two conditions are also true, then you value the variable largest with the value contained in n1. 

If n1 is less than n2, we know that n1 cannot be the maximum. The check with n2 and n3 therefore remains to be done. If n2 is greater than n3, then n2 is the maximum of the three variables. Otherwise, the maximum is n3.

We can easily see that it is possible to engage more if one inside the other. This is allowed, though not always encouraged. 

Syntax note: the curly brackets

Technically, Java allows us to omit the curly brackets from both the if blocks and the other blocks, as long as they contain only one instruction and no more.

Often this practice is used, and I admit that I do it myself: it has to be said that, in my opinion, we are losing legibility and clarity. Obviously, we are going to gain in compactness of the code. In the case of nested ifs, I recommend using them all the time.

Case 2: Selection structures with composite conditions

Another interesting case to analyse is the one where Boolean operators are used within the conditions. The classic example that can be analysed is one where you want to check that a given number falls within a range. Think, for example, of a software to make statistical evaluations of the school performance of a class.

Suppose we want to count how many grades are sufficient on a scale from 1 to 10, i.e. with a value greater or equal to six.

So let's see how we can do this, assuming we have already declared and initialised a variable called grade.

int counter = 0;
if( grade >= 6 && grade <= 10){
    counter = counter + 1;

The idea is therefore that a grade should be considered sufficient if and only if it is greater than or equal to 6 and at the same time less than or equal to 10. On a first attempt, someone might argue that a simple grade check >= 6 is sufficient. The problem arises, however, if there is an insertion error and a grade greater than ten is inserted. Our application would consider it sufficient, even if it is not a valid grade. One would then find oneself considering legitimate a situation that should be handled as a problem.

Case 3: condition with negation

Often, it may be convenient to use conditions that contain a denial within them. This may be for different reasons. It may be developmental convenience or mere readability. 

Let's see an example. As a case of use we can always keep the case of grade analysis. Let's assume that we want to check that a grade is valid. A solution might be similar to the one produced before. A far more readable and simple solution, in my opinion, is the following.

boolean voteValid = vote >= 6 && vote <= 10;
    //Manage error

So we notice that the code here is very easy to understand. In natural language, the condition can be read as "if not votoValido", which translated into Italian natural language, can be "if the vote is not valid". So we understand that the if will be executed only if the vote is not valid. This is the case when using a Boolean variable greatly simplifies code development.


This brief examination leaves us with some salient aspects. In particular, let us see how operators can be combined to form complex expressions. 

It is important, in these situations as in the rest of programming, to pay attention to code indentation. The risk is to write a code that is very complicated to read, if you don't insert the necessary spacing at the beginning of the line.

We will see later on that there is a valid alternative to the massive use of if constructs: the switch statement. 

It should be pointed out and reiterated that the analysis made is by no means exhaustive. The idea is to first give the fundamental tools to start writing code, and then to deepen some peculiar aspects.

To practice, it may be useful to solve the following exercise:

Write a SmallEven program that asks the user to enter a whole number and displays the message "Even and Small" if the number is even and is between 0 and 100, otherwise it prints the message "Not even and small". (Note: this program can be done using nested if-else or Boolean expressions. Try both versions).

The exercise comes from the  following document.

Alessio Mungelli

Alessio Mungelli

Computer Science student at UniTo (University of Turin), Network specializtion, blogger and writer. I am a kind of expert in Java desktop developement with interests in AI and web developement. Unix lover (but not Windows hater). I am interested in Linux scripting. I am very inquisitive and I love learning new stuffs.


Related Posts

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration