Java语法-类型转换
2022/3/6 14:15:40
本文主要是介绍Java语法-类型转换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
类型转换
由于Java是强类型语言,所以要进行有些运算的时候,需要用到类型转换
低---------------------------------------------------->高
byte,short,char,int,long,float,double>
小数的优先级大于整数
运算中,不同的类型,转换为同一类型后再运算
// 强制转换:(类型)变量名,高---低
//自动转换:低----高
注意点:
- 不能对布尔值进行转换;
- 不能把对象转换为不相干的类型;
- 在吧高容量转换到低容量的时候,强制转换;
- 转换的时候可能存在内存溢出,或精读问题。
public class demo04 { public static void main(String[] args) { int i = 128; byte b = (byte) i; System.out.println(i); System.out.println(b); System.out.println("============================="); double d1=3.2344043; System.out.println((int)d1); System.out.println("============================="); char c= 'a'; int d = c +1; System.out.println(d); System.out.println((char) d); //操作比较大的数的时候,注意内存溢出,比如: System.out.println("============================="); int money = 10_0000_0000; int years = 20; int total1 = money*years; //内存溢出; long total2 = money*years; //同样内存溢出,原因在于,计算的时候已经溢出,再赋值的,正确的做法如下: long total3 = money*((long)years); System.out.println(total1); System.out.println(total2); System.out.println(total3); } }
这篇关于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题)