1. Automatic type promotion in an expression:
When evaluating an expression, Java automatically implicitly promotes each byte, short, or char operand to an int type, and these types of wrapper types are also possible.
For example: shorts1 = 1;
S1 = s1 + 1;
The operand S1 in the s1+1 operation is automatically promoted to the int type, and the result of the s1+1 operation becomes an int type, and when assigned to a short type of S1, the compiler reports an error that requires a cast type . Need to change to short s1=1; s1= (short) (s1+1); The result is the short type.
For example: shorts1 = 1;
S1 + = 1;
+ = is an operator in the Java language that the Java compiler compiles correctly for its special handling.
2. Type promotion rules:
The values of byte, short, and char types are promoted to type int;
If one of the operands is of type long, the entire expression is promoted to a long type;
If one of the operands is of type float, the entire expression is promoted to float type;
If any one operand is of type double, the result is a double type.
For example:
BYTE b=1;
Char c= ' a ';
Short s=1024;
int i=50;
float f=2.0f;
Double d=.123;
Double result = (f * b) + (I/C)-(d * s);
In F*b, B is automatically promoted to the float type, and the result of this expression is the float type;
In I/c, C is automatically promoted to the int type, and the result of this expression is the int type;
In D*s, S is automatically promoted to the Doubl type, and the result of this expression is a double type;
Finally, float+int-double, the result is promoted to a double type, and the double type is the type of the final result.
3, test an int type data and float data operation, what type of test results
Public classTest { Public voidTestfloatf) {System. out. println ("float"); } Public voidTestDoubled) {System. out. println ("Double"); } Public voidTestinti) {System. out. println ("int"); } Public Static voidMain (string[] args) {Test T=NewTest (); inti =Ten; floatf =10f; T.test (f*i); }}
The final result is shown as float type
On the problem of automatic type promotion in Java operation