最近整理笔记刚好到强转这一块,所以简单的写一下,有错误的希望大家可以指出
整型,实型,字符型数据可以混合运算,运算时,不同类型的数据先转化为同一类型再运算
自动转化类型要从低级往高级转 byte,short,char—>int—>long---->float---->double
boolean 类型不能与整型进行转换
转化过程中可能会导致溢出或损失精度,比如int i=128,要强转为byte型时因为byte的最大值为127,所以128会溢出
public class ZiDongLeiZhuan {
public static void main(String[] args) {
char c='B';
int c1=c;
System.out.println("char类型自动转化为int类型的结果为 "+c1);
int b=12;
long b1=b;
System.out.println("int类型自动转化为long类型的结果为 "+b1);
int a=7;
float a1=a;
System.out.println("int类型自动转化为float类型的结果为 "+a1);
}
}
强转时 转换的数据类型应该是兼容的
大精度转小精度要强转
类类型不能强转
public class QiangZhuan {
public static void main(String[] args) {
int a=10;
byte a1=(byte)a;
System.out.println("int类型强转为byte类型的结果为 :" +a1);
float b=23.6f;
int b1=(int)b;
System.out.println("float类型转换为int类型的结果为 :" +b1);
} }
强转时 调用Math里面的round()方法,得出的结果是24,四舍五入了,网上有说强转时是通过去掉小数,不是四舍五入,但有的强转的结果却还是四舍五入的,所以我对此也有一定疑惑
运行结果