Java强制转换数据类型
执行结果截图:
代码:
public class MandatoryConvert {
public static void main(String[] args) {
int i1 = 128;
// int强制转换为byte(高容量转低容量)是强制转换,但是可能导致内存溢出
byte b = (byte)i1;
// int能强制转换为浮点double
// 不能强制转换为布尔值,例如int i,然后boolean d = i; 会报错
double d1 = i1;
double d2 = 23.7;
float d3 = -45.89f;
System.out.println(i1);
System.out.println(b);
System.out.println(d1);
// double类型被强制转换为int类型,高转低,小数点后的数值被截掉
System.out.println((int)d2);
// float类型被强制转换为int类型,高转低,小数点后的数值被截掉
System.out.println((int)d3);
System.out.println("==========================");
// c1是字符类型。注意:字符其实是以int类型存储的,字符a对应的Unicode值是整数97
char c1 = 'a';
// 此处的c1因为要进行+1运算,1默认是int类型,那么c1就会被强制转换为字符a所对应的Unicode值(int类型)97,那么和1相加的结果就是97+1=98
int d4 = c1 + 1;
// 输出d4的值,应该是98
System.out.println(d4);
// 将d5强制转换为字符,此时d4的值是98,对应Unicode表的b,所以打印的是字符b
System.out.println((char)d4);
System.out.println("==========================");
// 操作比较大的数时要注意溢出问题。JDK7及更高版本的新特性,为方便阅读大数值,数字之间可以用下划线分隔
int money = 10_0000_0000;
int years = 20;
// 相乘的结果默认是int类型, 值太大会内存溢出
int total1 = money * years;
// 由于money和years都是int类型,因此money*years的结果默认是int,还没来得及赋值给total2(大容量的long类型),内存就已经先溢出了
long total2 = money * years;
// 把years强制转换为long,money*years的结果就默认是long,内存就不会溢出了
long total3 = money * (long)years;
// 把money强制转换为long,money*years的结果就默认是long,内存就不会溢出了
long total4 = (long)money * years;
System.out.println(money);
System.out.println(years);
// 内存溢出,输出值错误
System.out.println(total1);
// 内存溢出,输出值错误
System.out.println(total2);
// 内存未溢出,输出值正确
System.out.println(total3);
System.out.println(total4);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探