Java强制转换数据类型编程练习
2021/12/14 9:18:01
本文主要是介绍Java强制转换数据类型编程练习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
执行结果截图:
代码:
public class MandatoryConvert { public static void main(String[] args) { int i1 = 128; byte b = (byte)i1; //int强制转换为byte(高容量转低容量)是强制转换,但是可能导致内存溢出 double d1 = i1; // int能强制转换为浮点double // 不能强制转换为布尔值,例如int i,然后boolean d = i; double d2 = 23.7; float d3 = -45.89f; System.out.println(i1); System.out.println(b); System.out.println(d1); System.out.println((int)d2); //double类型被强制转换为int类型,高转低,小数点后的数值被截掉 System.out.println((int)d3); //float类型被强制转换为int类型,高转低,小数点后的数值被截掉 System.out.println("=========================="); char c1 = 'a'; //c1是字符类型。注意:字符其实是以int类型存储的,字符a对应的Unicode值是整数97 int d4 = c1+1; //此处的c1因为要进行+1运算,1默认是int类型,那么c1就会被强制转换为字符a所对应的Unicode值(int类型)97,那么和1相加的结果就是97+com.cnblogs.www.1=98 System.out.println(d4); //输出d4的值,应该是98 System.out.println((char)d4); //将d5强制转换为字符,此时d4的值是98,对应Unicode表的b,所以打印的是字符b System.out.println("=========================="); int money = 10_0000_0000; //操作比较大的数时要注意溢出问题。JDK7及更高版本的新特性,为方便阅读大数值,数字之间可以用下划线分隔 int years = 20; int total1 = money*years; //相乘的结果默认是int类型, 值太大会内存溢出 long total2 = money*years; //由于money和years都是int类型,因此money*years的结果默认是int,还没来得及赋值给total2(大容量的long类型),内存就已经先溢出了。 long total3 = money*(long)years; //把years强制转换为long,money*years的结果就默认是long,内存就不会溢出了 long total4 = (long)money*years; //或者把money强制转换为long,money*years的结果就默认是long,内存就不会溢出了 System.out.println(money); System.out.println(years); System.out.println(total1); //内存溢出,输出值错误 System.out.println(total2); //内存溢出,输出值错误 System.out.println(total3); //内存未溢出,输出值正确 System.out.println(total4); } }
这篇关于Java强制转换数据类型编程练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)