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 : 479  
 
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

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

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…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

A Java approach: boolean variables

The previous time, we talked extensively about Boolean variables, trying to outline the main operations that can be carried out at a practical level.  Of all the cases examined, we have…

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…

Hashmap: hashing, collisions and first functions

Today we are going to study some concepts closely related to hashmaps. The concepts we are going to see are hashing and collisions. Hashing The idea of hashing with chaining is to…

Hashmap: Overflow Lists

In this short series of articles we will go to see how it is possible to create the Hashmap data structure in C. In the implementation we're going to use the…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

Data structures in Java - Linked Lists

With 2020 we are going to look at a new aspect of programming: data structures. It is often the case that everyone uses structures provided by the various programming languages.…

A Java approach: variables

Hello everyone and welcome back! Today we will begin a journey that will lead us to study, and possibly review, what are the basics of programming. We will start by talking…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

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