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

Creating simple CSS spinner-loader

In today's article we will show you how to animate a basic loader that spins when some predefined action is defined, such as loading an image. That can be used…

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

Django vs. Laravel: Market Share Comparison

There are two leading frameworks in the web development segment: Django and Laravel. In this article, we prepared a Django and Laravel comparison focusing on their market share so that…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

A Java approach: While loop

Hello everyone and welcome back! After having made a short, but full-bodied, introduction about cycles, today we are finally going to see the first implementations that use what we have called…

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…

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