A Java approach: condtional structures



Hello everyone and welcome back! The previous times we have introduced the concept of variable, trying to define some basic concepts about it. 

However, some situations suggest that the concept of variable alone is not enough to solve all the possible situations that may arise in front of us. A very banal example could be to understand if a number is odd or even. We immediately understand how the concept of variable alone cannot allow us to solve this problem, because after all, programming means solving problems, doesn't it? 

Throughout history, therefore, constructs have been developed and introduced that allow us to vary the flow of execution of the program itself. Let's try to understand better.

First of all, let's see a pseudo-code for solving the problem.

if the number is even
   do something 
otherwise
   do something else

You will immediately notice that there are two possible program executions.

The first involves the case in which the number is even, then you execute the instructions I have indicated, in a very informal way, with "do something". The second case, on the other hand, is the case of the odd number, where the actions performed are those named with "do something else".

The first important thing to say is that the two blocks of instructions are executed in an exclusive way. This means that if one group is executed then the other is not executed, and vice versa. This feature is fundamental precisely because the program execution flow is no longer one, but can have multiple developments. There are many developments, but they all have to be foreseen. 

The if-else construct

There are different decision constructs. The first and most basic is the if-else construct. In Java, the syntax for expressing it is as follows:

if(condition is true){  
    //Instructions to be carried out if the condition is true
} else {
    //Instructions to be carried out if the condition is false
}

You can easily see that two fundamental blocks are highlighted. The if block and the other block. Let's see how the fulcrum of the whole construct is the condition. This notion introduces us to a new type of value: the Boolean value. Basically, condition can assume only two possible values: true or false

We will see next time how Boolean values work. 

Let's now consider the solution to the problem that was first posed regarding odd and even numbers.

int a = k;
if(a % 2 == 0){
    System.out.println("Even");
} else {
    System.out.println("Odd");
}

The solution is quite simple, as the fundamental skeleton of the problem is the if-else construct. It is up to the programmer to choose what to insert inside the two blocks. 

A small note about the notation I used: the k of the variable initialization is a compact way to say that that k can be replaced with any integer value.

This example is ideal for introducing a new operator: the %. This operator allows us to calculate the rest of a division. When we write a % b we are then calculating the rest of the division of a for b. For example, writing 5 % 2 results in 1, because 1 is the rest of the division between 5 and 2.

The if-elseif-else construct

Sometimes it can happen that there are a number of conditions that have to be checked exclusively. Therefore, having, for example, three conditions c1, c2 and c3, check them in an exclusive signigic way that, if c1 is true, neither c2 nor c3 are checked. If c2 is true, c3 is not checked. How to do this?

An inexperienced reader could say that a series of ifs could be the solution. You could then write a solution similar to the following

if(c1 true){
    // do something
}else{
    if(c2 true){
        //do something else
    }else{
        if(c3 true){
            //do something else
        }
    }
}

This solution works without a shadow of a doubt, but it is still unnecessarily complex and very unattractive.

The if-elseif-else construct comes to our aid. Let's see the syntax:

if(true condition){

}else if(other true condition){

}else{

}

So let's see the introduction of a new block of code, defined by the else if section. This section is evaluated only if the if condition is false. Let's see a possible example.

The problem to solve is the following: given a variable, print it if it represents a positive number, print the string "zero" if its value is equal to zero and print its value multiplied by two if it is a negative value. 

A possible solution is this.

int a = k;
if(a > 0){
    System.out.println(a);
}else if(a == 0){
    System.out.println("zero");
}else{
    System.out.println(a*2);
}

As before, a = k means that k can be replaced with any integer value. 

One question that may arise is: how many more branches if I can add? The answer is: as many as you want. Generally, there is a tendency to contain the number, as the code becomes unreadable and unattractive as the else if grows. We'll see later on that you tend to opt for a different solution, which tends to make the code more readable and clearer, regardless of the growth of the conditions to be checked.

If construct

Left for last, the construct if is the elementary brick at the base of the two shown above. The concept is really simple. If a given condition is true, then I perform actions and then continue with the normal flow of the program. 

The syntax is the following one.

if(true condition){
    //code
}

A possible example is the following: given a variable, print it and if it is even add 1.

int a = k;
if(a%2 == 0){
    a = a + 1;
}
System.out.println(a); 

We therefore see that it is only possible to perform operations in certain cases. In this way, you can vary the behaviour of the program according to the configuration of the variables at that given moment.

This introduction may seem rather theoretical, but later we will see some examples that allow us to see some situations of application of this concept.

A bit of theory: the configurations of the variables

The concept of variable configuration is indispensable to understand in order to fully grasp the meaning of some sentences. 

When we refer to a configuration, we are referring to the set of variables and values that those variables have at a specific time of code execution.

If we want to somehow represent a configuration of variables, we could use a notation like this: { variable1 = valueVariable1, variable2 = valueVariable2, ... , variabilen = valueVariabilen }.

 
 
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

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…

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…

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