您现在的位置是:首页 > 文章详情

Java 基础 之 常量类型转换

日期:2018-07-18点击:338

http://www.verejava.com/?id=16992572054911

/* 类型转换分为以下几种情况 1. 整型类型转换 2. 浮点类型转换 3. 布尔类型转换 4. 字符类型转换 */ public class TypeConvert { public static void main(String[] args) { byte a1=1; int b1=2; //小整数类型转换成大整数类型, 直接转换 b1=a1; System.out.println(b1); byte a2=1; int b2=2; int b3=128; //大整数类型转换成小整数类型, 需要强制类型转换, 并且可能损失精度. 将会把高位切除. a2=(byte)b2; a2=(byte)b3; System.out.println(a2); byte c1=1; float c2=10.3f; //整数转浮点型,直接转换 c2=c1; System.out.println(c2); byte d1=1; float d2=10.3f; float d3=128.2f; //浮点类型转整型 直接去掉小数部分, 需要强制类型转换, 并且可能丢失精度 d1=(byte)d2; d1=(byte)d3; System.out.println(d1); //布尔类型不能转换成其他类型, 其他类型也不能转换成布尔类型 boolean e1=true; //e1=(boolean)1; char f1='a'; int f2=1; char f3='b'; int f4='b'+1; char f5='b'+1; //整型可以转换成 字符类型,需要强制类型转换,整型也可以转换成字符型,转换的规则为 ACSII 码表 f1=(char)f2; f2=f3; System.out.println(f1); System.out.println(f2); System.out.println(f4); System.out.println(f5); //字符串连接 + 转换 String str="hello"; String str2=str+1; String str3=str+2.5; String str4=str+true; String str5=str+'F'; //字符串跟其他基本类型相加 其他类型自动转换成字符串连接 System.out.println(str2); System.out.println(str3); System.out.println(str4); System.out.println(str5); } } /* 总结: 1. 类型转换小数值到大数值转换 byte<short<int<float<long<double 2. 整型 默认是 int 型, 浮点型 默认是 double 型 */

http://www.verejava.com/?id=16992572054911

原文链接:https://yq.aliyun.com/articles/614405
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章