Automatic conversion
Class Hello{public static void Main (string[] args) {//auto-convert int a = 5;byte b = 6;int C = a + B; System.out.println (c);}}
A is an int type, B is a byte type when the two are adding operations (depending on the same type of addition or similar) because the range of int is larger than the range of byte, the JVM will automatically convert B to int type
Forced conversions
cast int a = (int) 8.8;
The cast is the one that is preceded by the type you want to convert.
Here's a more special
Class hello{public static void Main (string[] args) { byte b = 3;//correct int x = 3;//correct b = x;//error }}
The above code will error when compiling, the type of the constant 3 is an int int type can be assigned to a variable of byte but b=x this time. Because the constant optimization mechanism is only for constants that do not target variables, which means that a large range cannot be assigned to a small range unless the cast type
Look at the following and follow the above principles
Class Hello{public static void Main (string[] args) {byte b1=3,b2=4,b;//correct b = b1 + b2;//error because B1 B2 This time is variable (constant optimization mechanism only for constants not for variables) b = 3 + 4;//Correct}}
Looking at an example
Class hello{public static void Main (string[] args) {short s = 1; s = s + 1;//error and short s = 1; s+=1;//correct }}
The above code is no different from the surface, why is the second one correct?
The first calculation will automatically convert s to int type in the addition operation (low precision to high precision) and then the result is that the int type is not suitable for assigning to the short type (high precision cannot be assigned to a low precision type) so the error will be correctly written as the following code
Class Hello{public static void Main (string[] args) {Short S = 1;s = (short) (S + 1); System.out.println (s);}}
Then why is the second possible?
Because the operators of + =,-+, *=, and/= are more specific, they have the effect of forcing type conversions.
A detailed description of the Java Type conversion (auto-convert and cast)