Detailed explanation of type conversion in decryption of Java

  • 2021-07-10 19:45:57
  • OfStack

As we all know, the data types in Java are strong data types, and the conversion between basic data types is especially fixed. When a data type with narrow data width (such as int) is converted to a data type with wide data type (such as double), the narrow data type will be widened, and automatic type conversion can be completed, which is called implicit conversion.

For example: There is no problem with the following code, the result is correct, and the result will not change. The difference is that the accuracy of the result is improved.


intintScore = 96;
doubledoubleScore = intScore;

Then, if you try to convert a wide data type (such as double) to a narrow data type (such as float), the compiler will prompt a compilation error. If you want to compile, you need to force a type conversion. Then, the data will be truncated at this time. The result is:

1. The data is correct, but the accuracy is reduced;

2. The data is incorrect and overflow occurs;

For the first case above, it is better to understand. Let's take an example:


float floatWeight= 63.5; // Compilation error 
double doubleWeight= 63.5;

The first statement above will prompt a compilation error, because when the compiler sees 63.5, it will treat it as an double type and assign an double type to an float type, but the compilation will not pass. The recommended solutions are:


float floatWeight = 63.5f;

Of course, you can also cast to float type:


float floatWeight = (float)63.5;

In fact, the essence of the above statement is to cast the data of double type into float type, and truncation occurs. Although the size of the data has not changed, the accuracy of the data has decreased.

Similarly:


doubleWeight = floatWeight; // Implicit conversion 
floatWeight = (float)doubleWeight;// Cast 

Now, the question is, since it is truncation, how can there be overflow? Let's look at an example first:


shorti = 150;
shortj = 75;
byteb = (byte) i; 
byted = (byte) j; 
System.out.println("b = " + b);
System.out.println("d = " + d);

The output of the above code is:

b = -106
d = 75

Seeing the results, you can't help but ask why b=-106. This is due to an overflow during the cast. Because 150 is beyond the maximum range that byte can represent (-128 ~ 127).

So how did-106 come from?

i = 150, i = 0000 0000 1001 0110 in binary, short type is 2 bytes, 16 bits, and the highest bit 0 is a positive number. When i is cast to byte type, the high bit is truncated, i = 1001 0110. In a computer, it is represented by a complement, and the highest bit 1 represents a negative number, so if it is represented by the original code: i = 1110 1010, which is exactly the decimal number-106.

At this point, it explains why truncation may also overflow.


Related articles: