Explicit Implicit Java Conversion

With the following code:

Float a = 1.2; 

there is an error because it takes a decimal value as a double value, and double is a larger data type than float .

Now it accepts the integer type by default int . So why the following code does not give any errors?

 Byte b = 20; 
+6
source share
2 answers

The compiler is smart enough to understand that the representation of bits 20 ( int value) can fit in a byte without data loss. From the Java Language Specification ยง5.1.3 :

The narrowing of the primitive conversion from double to float is determined by the rounding rules of IEEE 754 ( ยง4.2.4 ). This conversion may lose accuracy, but also lose range, resulting in a float zero from a non-zero double and a float infinity from a finite double. A double NaN is converted to float NaN, and infinity double converted to infinite infinity float .

Narrowing the conversion of a signed integer to an integral type T simply discards everything except n bits of the least significant bit, where n is the number of bits used to represent type T. In addition to the possible loss of information about the value, a numerical value can lead to the sign of the resulting values โ€‹โ€‹will differ from the sign of the input value.

See also this thread .

+7
source

There are no implicit narrowing transforms at all - the only exception is constant expressions, and they are explicitly allowed by JLS 5.2:

Furthermore, if the expression is a constant expression (ยง15.28) of type byte, short, char or int:

* Narrowing the primitive conversion can be used if the type of the variable is byte, short or char, and the value of the constant expression is represented in the type of the variable.

There is no mention of implicit narrowing of conversions allowed for floating point numbers, so they are prohibited in accordance with the general rule.

+1
source

All Articles