表达式的类型转换
一段小程序来解释表达式中的各个数据类型的转换机制。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | package com.liaojianya.chapter1; /** * This program demonstrates the convertion of data type. * @author LIAO JIANYA * */ public class TypeConvert6_17 { public static void main(String[] args) { char ch = 'a' ; short a = - 2 ; int b = 3 ; float f = 5 .3f; double d = 6.28 ; System.out.println( "ch / a = " + ch / a); System.out.println( "the type of (ch / a) is : " + getType((ch / a))); System.out.println( "d / f = " + d / f); System.out.println( "the type of (d / f) is : " + getType((d / f))); System.out.println( "a + b = " + (a + b)); System.out.println( "the type of (a + b) is : " + getType((a + b))); System.out.println( "(ch / a) - (d / f) - (a + b) = " + ((ch / a) - (d / f) - (a + b))); System.out.println( "the type of ((ch / a) - (d / f) - (a + b)) is : " + getType(((ch / a) - (d / f) - (a + b)))); } public static String getType(Object o) { return o.getClass().toString(); } public static String getType( int o) { return "int" ; } public static String getType( char o) { return "char" ; } public static String getType( short o) { return "short" ; } public static String getType( float o) { return "short" ; } public static String getType( double o) { return "double" ; } } |
运行结果:
1 2 3 4 5 6 7 8 | ch / a = - 48 the type of (ch / a) is : int d / f = 1.1849056177353188 the type of (d / f) is : double a + b = 1 the type of (a + b) is : int (ch / a) - (d / f) - (a + b) = - 50.18490561773532 the type of ((ch / a) - (d / f) - (a + b)) is : double |
分析:
1)占用字节较少的数据类型转换成占用字节较多的数据类型。
2)字符类型会转换成int类型。
3)int类型会转换成float类型。
4)表达式中出现double,则其他操作数也会转换成double类型。
5)总结:大鱼吃小鱼:占字节多的替换占字节少的;精度高的优先;优先级排序:byte,short,int,long,float,double。
烧不死的鸟就是凤凰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)