Recently, the basic knowledge of the javase has been read again, the first place I think the error of the local summary.
the difference between the variable addition and the constant addition of the interview question
Is there a problem with the following code
BYTE B1 = 3;
byte b2 = 4;
BYTE B3 = b1 + b2;
byte B4 = 3 + 4;
B3 type conversion error, need to cast to byte type, b4 correct
Answer this question from both sides.
B1 and B2 are two variables, and the values stored in the variables are variable, so the JVM is unable to determine the specific values in the program's operation.
Variables of type Byte are automatically raised to the int type when they are operating.
So assigning the int type obtained by B1+B2 to B3 needs to be cast to the byte type.
and 3 and 4 are constants, Java has a constant optimization mechanism, in the compilation will directly to the 3 and 4 of the results assigned to B4, so b4 no error.
This leads to the problem of implicit conversions and explicit conversions (casts)
Ii. implicit conversions and explicit conversions of basic data types (casts)
Implicit conversions:
The data type with a small value range and the data type with large range of values can be calculated, and the small data type will be promoted to large and then operation.
Explicit conversions:
Assigning data of a data type with a large range of values to a data type that has a small range of values requires a cast, otherwise a type conversion error is reported. A cast that exceeds the value range of the assigned data type will be different from the result you expect.
summed up as
When mixed, Byte,short,char does not convert to each other, automatic type elevation to int type, and other types of mixed operations are small data types raised to large
byte,short,char–> int–> long–> float–> Double
Well, you know that the long type is 8 bytes, the float type is 4 bytes, the long type and the float type who is the bigger and the smaller.
Three, long, and float range sizes
According to IEEE754, the float type is 4 bytes, that is, 32 bits, 1 bits is a sign bit, 8 digits is a digit, and 23 bits are decimal places. From 00000000 to 11111111, the range of indices ranges from 0 to 255, 0 represents infinity, and the remaining 0,255 per one subtracts 1-254, that is, 127 to 126. So the range represented by float is larger than the range represented by long.