Java SE7新特性之在数值型的字面值中使用下划线
2014-01-04 13:50
471 查看
在Java SE 7及后续版本中, 数值型的字面值中的数字之间可以出现任何数量的下划线。例如,这个特性可以让你将数值型的字面值中的数字分隔成组,这样可以提高代码的可读性。
比如, 如果你的代码包含有许多位的数字, 你可以使用下划线将这些数字分成三组, 和使用标点符号(逗号或者空格)作为分隔符一样。下面的例子展示了在数值型的字面值中可以使用下划线的其它的一些方式:
long creditCardNumber = 1234_5678_9012_3456L; long socialSecurityNumber = 999_99_9999L; float pi = 3.14_15F; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; long maxLong = 0x7fff_ffff_ffff_ffffL; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010;
你只能将下划线置于数字之间; 以下地方不能放置下划线:
数字的开头或结尾
浮点数中靠近小数点的位置
F或
L后缀之前
期望放置一串数字的地方
下面的例子展示了数值型的字面值中有效和无效的下划线位置 (高亮的) :
float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent to a decimal point float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal point long socialSecurityNumber1 = 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffix int x1 = _52; // This is an identifier, not a numeric literal int x2 = 5_2; // OK (decimal literal) int x3 = 52_; // Invalid; cannot put underscores at the end of a literal int x4 = 5_______2; // OK (decimal literal) int x5 = 0_x52; // Invalid; cannot put underscores in the 0x radix prefix int x6 = 0x_52; // Invalid; cannot put underscores at the beginning of a number int x7 = 0x5_2; // OK (hexadecimal literal) int x8 = 0x52_; // Invalid; cannot put underscores at the end of a number int x9 = 0_52; // OK (octal literal) int x10 = 05_2; // OK (octal literal) int x11 = 052_; // Invalid; cannot put underscores at the end of a number
本文翻译自Oracle官方文档http://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html,如有不正确指出,敬请指正,谢谢!
相关文章推荐
- 【Java】 txt文件加密
- Hiberante之反向工程应用(eclipse和myeclipse)
- MyEclipse 断点打不上 提示 absent line number information
- 关于springmvc 返回json乱码
- Struts2 单文件上传遇到的问题及解决方法
- window7下Java环境变量配置图解
- struts2,项目经验总结(持续更新中)
- MyEclipse,工程项目经验总结(持续更新中)
- ubuntu 安装jdk7
- [转]如何优化Java垃圾回收机制
- myeclipse 重新关联项目和svn
- Java中读取文件进度条的实现
- 数据挖掘apriori算法Java代码实现
- java软引用、弱引用、虚引用
- Eclipse
- eclipse导入ejabberd
- java工程转变为web工程之后可以部署到服务器中
- JAVA内存模型及volatile关健词
- java 用jni调用so全过程
- net.sf.json.JSONException: java.lang.NoSuchMethodException: ***.SubjectSum.<init>()