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