Because Java is a strongly typed language, it is sometimes used in operationsType conversion。
Integer, constant and character type data can be mixed.
In operation,Different types of data are converted to the same type first, and then perform the operation.
The type conversion level can be divided from low level to high level, mainly according toMemory capacity of data typeTo divide,The larger the capacity, the higher the level, andFloating point type has higher priority than integer type。
When a low-level data type is converted to a high-level data type, theAutomatic type conversion。
When a high-level data type is converted to a low-level data type, it must beCast type。
Type conversion level:
/*Low level ----------------------------------------------- high level*/ /* byte -> short,char -> int -> long -> float -> double */
Type conversion rule:
- Cannot type convert boolean type.
- You cannot convert an object type to an object of an unrelated class.
- Cast must be used when converting a high-level type to a low-level type.
- Automatic type conversion cannot be performed between byte type to char type, short type and char type.
1、 Automatic type conversion
- Basic data types with small numerical range can be automatically converted to basic data types with large numerical range.
- Automatic type conversion cannot be performed when byte type is converted to char type.
- Short type and char type are converted to each other, and automatic type conversion is not allowed.
- When char type is converted to a higher level type, automatic type conversion can be performed.
byte byteNumber = (byte)1; short shortNumber = byteNumber; char charNumber = (char) shortNumber; int intNumber = charNumber; long longNumber = intNumber; float floatNumber = longNumber; double doubleNumber = floatNumber; System.out.println(doubleNumber);//1.0
2、 Cast type
- Used to explicitly convert a numeric type. The converted data type must be compatible.
Syntax:‘(‘ + type + ‘)’ + value
be careful:Cast may causeoverfloworLoss accuracyFor example:
/*Because the memory capacity of byte type is 8 bits and the maximum value is 127, when the value 128 of int type is cast to byte type, overflow will be caused*/ System.out.println((byte) 128);//-128 /*The conversion from floating-point number to integer is obtained by discarding decimals rather than rounding, so precision will be lost*/ System.out.println((int) 99.9);//99 System.out.println((int) -99.99f);//-99