Java (data type conversion)
I. Data Type Conversion
It can be divided into "automatic type conversion" and "forced type conversion"
Ii. Automatic type conversion
Low level ------ high level
byte b=7; int i=b; System.out.println("i= "+i); double d=i; System.out.println("d= "+d); double dw=5+5.6*4+'A'; System.out.println("dw="+dw);
Result:
I = 7
D = 7.0
Dw = 92.4
Iii. Forced type conversion
High level --- low level, may cause data loss
Add parentheses before the variable to convert (type) the variable
double d = 3.6; int i =(int) d; System.out.println("i= "+i); int x=786; short sh = (short)x; System.out.println("sh="+sh); byte b = (byte)x; System.out.println("b= "+b);
Result:
I = 3
Sh = 1, 786
B = 18
double d =84.54; int c= (int)d/2; System.out.println(c);
Result: 42
4. Any data type is transformed to String
String str = "Hello"; int x = 30; str=str+x; System.out.println("str= "+str);
Result:
Str = Hello30
int i =1; int j=2; System.out.println("1+2= "+1+2);
Result:
1 + 2 = 12