Automatic type conversion:
Integer, Real (constant), character-type data can be mixed. Operations, different types of data are converted to the same type first, and then the operation is performed.
Conversions from low to advanced.
low ------------------------------------> High
Byte,short,char-> int -> Long-> float - > Double
data type conversions must meet the following rules:
1. A type conversion cannot be made to a Boolean type.
2. object types cannot be converted to objects of unrelated classes.
3. forced type conversions must be used when converting large-capacity types to small-capacity types.
4. The conversion process may result in overflow or loss accuracy, for example:
int i = 128;
byte B = (byte) i;
because the byte type is 8 bits, the maximum value is 127, so when cast to the int type value it can cause overflow.
5. the conversion of floating-point numbers to integers is obtained by discarding decimals, rather than rounding, for example:
(int) 23.7 = = 23;
(int) -45.89f = =-45
Automatic type conversion:
the number of bits that must be satisfied before the conversion data type is lower than the converted data type, for example : The short data type has a number of digits and can be automatically converted to a number of digits int type, the same float data type has a number of digits and can be automatically converted to bit of Double type.
Instance
public class zidongleizhuan{
public static void Main (string[] args) {
Char c1= ' a ';// define a char type
int i1 = C1;//char automatic type conversion to int
System.out.println ("Char automatic type is converted to int after the value equals " +i1);
char c2 = ' a ';// define a char type
int i2 = C2+1;//char type and int type calculation
System.out.println ("Char type and int calculated value equals " +i2 ");
}
}
The result of the operation is :
Char automatic type converted to int has a value equal to
Char type and int calculated values equal to
Forcing type conversions
1. the condition is that the data type of the conversion must be compatible.
2. format:(type) value type is an instance of the data type to enforce type conversion:
Instance
public class qiangzhizhuanhuan{
public static void Main (string[] args) {
int i1 = 123;
byte B = (byte) i1;// coercion type conversion to byte
SYSTEM.OUT.PRINTLN ("int forces the value of type conversion to byte equals " +b);
}
}
Operation Result:
int casts a value equal to 123 after the type is converted to byte
implicitly enforcing type conversions
1. the default type for integers is int.
2. This is not the case with floating-point types, because the float type must be followed by F or Fafter the number.
This section explains the basic data type of Java. The next section explores the different types of variables and their usage.
Java Data type Conversions