Java基础04-类型转换
类型转换
1.转换类型等级
低—————————————————————>高
byte,short,char—>int—>long—>float—>double
自动类型转换:低——>高
强制类型转换:高——>低
2.自动类型转换
char c1 = 'a';
int i2 = c1; //char类型自动转换为int类型
System.out.println("char自动类型转换为int后的值为:" + i1); //查ASCII表,a对应97,输出97
char c2 = 'A';
int i2 = c2 + 1;
System.out.println("char类型和int计算后的值为:" + i2); //A对应65,65+1=66,输出66
3.强制类型转换
语法格式:
(type)var
double x = 3.14;
int nx = (int)x; //nx=3
char c = 'a';
int d = c + 1;
System.out.println(d); //d=98
System.out.println( (char)d ); // (char)d = 'b';
4.注意
1.不能对boolean值进行转换。
2.容量大—>容量小,必须使用强制转换。
3.转换过程中可能造成内存溢出或精度损失。
5.感想