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

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…

Dates in local format with Javascript

In the articles we have about dates in JavaScript we were missing one about how to create dates in local format with JavaScript. That is to say, being able to…

Formatting hours in Javascript

Continuing with the set of articles that talk about internationalisation elements, like the previous one where we talked about relative dates in JavaScript, we will see in this one how…

Request data with prompt in JavaScript

After having published several articles about how to manipulate arrays and dates, today I will publish a post that some of you will find too basic and others will find…

Relative dates in JavaScript

One of the interesting things about the internationalisation library represented in the Int object is the handling of relative dates in Javascript. This handling allows us to represent a date…

How to access webcam and grab an image using HTML5 and Javascript

We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need…

The JavaScript forEach loop

We have already talked about how to handle some of loops  types in Javascript including for, for-in and for-off loops. In the case of today we are going to see how…

What are React Hooks and what problems they solve

Working with React, - and before the release of Hooks in version 16.8 -  there was always the possibility to create components in three different ways based on a number of…

Flattening arrays in JavaScript

When we are handling arrays that are arrays or have multiple dimensions it can be very useful to know how to flatten arrays in JavaScript. That is to say, to…

How to populate an array with random numbers in JavaScript

Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability…

How to populate an array with numbers in JavaScript

Populate an array with numbers in JavaScript The first step is to initialise the array. So today we are going to see a simple way to do it and see how…

Top Javascript Libraries and Frameworks Part 2

What are JavaScript frameworks?   JavaScript frameworks are application frameworks that allow developers to manipulate code to meet their particular needs. Web application development is like building a house. You have the option…

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