A Java approach: variables - use case

Begin with a practical example

by Alessio Mungelli Date: 22-10-2020 java jdk jre coding programming variables explanation use case tutorial examples


Hello all friends and welcome back!

After the introduction made on the variables, we try to analyse some critical issues that may arise in quite common situations. Let's start by analysing some practical examples.

Example 1: division that returns a non-integer result

The first critical case that might arise for those who approach coding is a problem related to the following code.

public class Main {
    public static void main(String[] args){
        int a = 1;
        int b = 2;
        System.out.println("a/b = "+a/b);
    }
}

By executing this code, the output we will get is: a/b = 0 . Clearly this is not the result we expect to get. Before we see the solution, let's analyse the code.

In this case, two variables a and b are created by assigning values 1 and 2 respectively. Then there is the terminal print instruction which is System.out.println() . Inside the round brackets we will have to insert the content we want to print. We can concatenate a fixed string, inserted between double quotes to a number using the + operator. We will see later on some common functions that can be used.

The fact remains that this short and simple code does not work correctly. What we need to do is to think about the data type we have chosen. 

What we have to ask ourselves is: are we sure that the result of a division is always an integer number? The answer is quite simple: no

At this point you are wondering how to solve this situation. Let's look at a couple of possible solutions.

public class Main {
    public static void main(String[] args){
        int a = 1;
        int b = 2;
        System.out.println("a/b = "+(float)a/b);
    }
}

To the unwise eye, this solution might seem identical to the one we have seen as problematic. There is actually a small difference in printing instruction. In fact I added (float) next to the number to be printed, which in this case is a/b.

This operation, which we will analyse later, is called cast or casting. To give a first smattering, it does nothing more than convert a value from one type to another. This is necessary because the two variables are int type and consequently, even their division will return an int quotient. But in reality, as we said, the quotient must be a decimal number, so float or double. Hence the need to make a "conversion".

It is right to reiterate that this definition of cast is neither precise nor complete. It only serves to give a first practical tool to solve a rather common problem. We will see its use later on.

A second solution, much more banal but equally effective, is to make one of the two variables a decimal number. 

public class Main {
    public static void main(String[] args){
        float a = 1;
        int b = 2;
        System.out.println("a/b = "+(a/b));
    }
}

This works because, in general, an operation between a decimal number and an integer returns a decimal number, where by decimal we also mean a number of the type 4,0000.

For both solutions, the output of the program will be a/b = 0.5 , which is exactly the result we expect. Obviously, by changing the values assigned to a and b, everything continues to work correctly. We'll see later on how to remove any unwanted zeros from the decimal expansion.

Example 2: assignment of values of a different type than the variable

One mistake that one tends to make often at first is to mistake the values to be assigned to the variables. Let's try to understand better. 

It can happen, sometimes, to try to assign a decimal number to a whole variable or a whole number to a float variable. Let's see an example.

public class Main {
public static void main(String[] args){
float a = 1;
int b = 2.5;
System.out.println("a="+a);
System.out.println("b="+b);
}
}

This program does not work. Let's analyse the reasons. The first assignment works, as 1 can be interpreted as 1.0000 and therefore as a float number. The second is the problematic one. What we have to ask ourselves is: 2.5 is a whole number? Well, clearly not. In fact, running the program, we get this error message: Error:(6, 17) java: incompatible types: possible lossy conversion from double to int . To the most attentive reader, at least one question will arise. How come the error message mentions double, when there is not even a shadow of double in my code?

The reason lies in the fact that, by default, a decimal number is interpreted as double. To tell the compiler that that value is a float, then we should write a line like this. 

int b = 2.5f;

In this way, 2.5 will be recognised and treated as float and not double. This is demonstrated by the error message that appears: Error:(6, 17) java: incompatible types: possible lossy conversion from float to int. 

We must now understand what that error message means. Banally, it is telling us that in the conversion from float to int, we could lose information. This is why the second assignment is not allowed. So let's remember that, unless we see particular situations, it is not allowed to assign values that are not of the same type as the variable. 

Entry point: the main

The last concept worth exploring this time is that of main. 

In all the examples presented today, we have written all our code within an entity we have defined as:

public class Main {
public static void main(String[] args){
//scrivi qui il codice
}
}

What we have done, defining that public static void main(String[] args) is to define what is called entry point, that is the point from which the program starts its execution.

As soon as we run our program, its execution will start from the instructions contained in the main. For the examples we will develop in these first few times, all the code will be written inside the main.

One thing I'd particularly like to stress is the meaning of inside the main. It's an obvious concept for many people, but not trivial for those who approach programming. When we say "inside the main" we mean that the code must be inside the open and closed brackets after the definition. 

public class Main {
    public static void main(String[] args){
        //write your code here
    }
}

The code should then be written inside the brackets highlighted in red.

That's all for this time too. I invite you to experiment a lot. Experimenting is the only way to learn how to program. You have to try and throw yourself into it. Otherwise, it would be like trying to learn to swim by reading a book in the library.

 
by Alessio Mungelli Date: 22-10-2020 java jdk jre coding programming variables explanation use case tutorial examples hits : 848  
 
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

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…

How to Send Email from an HTML Contact Form

In today’s article we will write about how to make a working form that upon hitting that submit button will be functional and send the email (to you as a…

Top JavaScript libraries and frameworks part 1

JavaScript libraries and frameworks make it easy to develop websites and applications with a wide variety of features and functionality, all with dynamic, flexible and engaging features. According to a 2020…

Looping through a matrix with JavaScript

We were already talking about how to multiply arrays in JavaScript and we realised that we had not explained something as simple as traversing an array with Javascript. So we…

How to multiply matrices in JavaScript

It may seem strange to want to know how to multiply matrices in JavaScript. But we will see some examples where it is useful to know how to perform this…

JavaScript Formatting Date Tips

Something that seems simple as the treatment of dates can become complex if we don't take into account how to treat them when presenting them to the user. That is…

Top tools for UX design and research

This article is a compilation of the "ux tools" I have tested in recent years. I've separated the tools by categories, although I recommend you to take a look at all…

How to make a multilingual website without redirect

Today, we're going to talk about how to implement a simple language selector on the basic static website, without the need of any backend or database calls or redirection to…

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