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 : 2343  
 
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 upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Hidden Gmail codes to find a lost e-mail

If you have a lot of emails in Gmail, there are a few codes that will help you find what you need faster and more accurately than if you do…

How to download an email in PDF format in Gmail for Android

You will see how easy it is to save an email you have received or sent yourself from Gmail in PDF format, all with your Android smartphone. Here's how it's…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…