Type conversion
-
Because Java is a strongly typed language, some operations require type conversions
-
Convert from low-level to high-level.
Low -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > high byte, short, char - > int - > long - > float - > doubleCopy the code
-
In an operation, different types of data are first converted to the same type and then computed
Cast (from high-level to low-level)
Grammar ((Type) Variable name
)
int i = 128;
//byte b = i; An error is reported directly in the Java compiler
byte b = (byte)i;
// Output: 128
System.out.println(i);
// Output: -128; Because of memory overflow
System.out.println(b);
// Output: 12; Because of the loss of accuracy
System.out.println((int)12.3);
// Output: -1; Because of the loss of accuracy
System.out.println((int) -3.14);
Copy the code
Automatic type conversion (from low-level to high-level)
int i = 128;
double b = i;
// Output: 128
System.out.println(i);
// Output: 128.0
System.out.println(b);
Copy the code
Data type conversions must meet the following rules:
- Boolean types cannot be cast.
- An object type cannot be converted to an object of an unrelated class.
- Casts must be used when converting a large type to a small type.
- Overflow or loss of accuracy may occur during conversion
- Because byte is 8 bits and has a maximum of 127, an overflow occurs when an int is cast to byte at 128.
- Floating-point to integer conversions are achieved by dropping decimals, not by rounding
Beware of overflow when working with large numbers
//JDK7 new feature, numbers can be separated by underscores
int money = 10 _0000_0000;/ / 1 billion
// Output: 1000000000
System.out.println(money);
int total = 20 * money;
long total2 = 20 * money;
// Output: -1474836480; Because it overflowed in the calculation
System.out.println(total);
/* Output: -1474836480; Although total2 is of type long, it does not overflow, but: the result of the calculation is based on, the value of the calculation is based on the previous type 20 and money is int, so it is also int */
System.out.println(total2);
long total3 = 20 * ((long)money);
/* Output: 20000000000; First cast money to long and then calculate the result, again choosing the type with the highest type level */
System.out.println(total3);
Copy the code