Conversion Of Mathematical Types

It may happen that we store some variables in type A, then at some point we need the same data, but in type B.

The simplest example is the one in which we have the number declared as int, and then we want to divide it. also by type int. As we know from the previous post, then we will have to deal with a complete division and we will get false results. There are some rules that can be presented in 4 simple points:

• If one of the operands is double, then the other will also be changed to double
• Or, if any of the operands is float, then the other will also be float
• Or, if one of the operands is long, the other will also be changed to long
• When none of the higher types are found, both types will be converted to int

In short, we can imagine that in mathematical operations all variables are automatically converted by the Java virtual machine into the highest available type.

We see this action in the above example. First, we declare two variables a and b, respectively the types int, and double. Next, we assign the result of operation b / a to the variable c. What can we expect ?

Before devision, the variable type ‘a’ is converted to double so that we get a floating-point result, not an integer result. Be careful not to make a mistake and try to force a downward conversion, for example from a double to an int. This will cause the program to fail to compile.

In the above example, we try to assign to the variable c the type int and then we devide b / a, which is the floating point number 2.7. In this case, the compiler will fail.

Okay, but what if we actually need to replace the double type with an int?

Casting (Explicit Conversion)

We can force a conversion from one type to another by placing the target type in round brackets.

In this case, we will not see the error anymore. However, we must be aware that doing so involves the loss of some data, in this case cutting the fractional part. In the above example, the first division is followed by the cutting (not rounding) of the result. To obtain the approximate value of the result, the Math.round () method should be used.

We can therefore present the conversion as an implicit projection:

Fortunately, we do not have to write it down. Java will do it for us automatically.