Java小陷阱
基本数据类型与字符串的连接
在Java中,+不仅可作为加法运算符使用,还可作为字符串连接运算符使用。
当把任何基本数据类型的值与字符串值进行连接运算时,基本类型的值将自动类型转换为字符串类型。
public class PrimitiveAndString
{
public static void main(String[] args)
{
//下面的语句输出 7Hello!
System.out.println(3 + 4 + "Hello!"); //下面的语句输出 Hello!34
System.out.println("Hello!" + 3 + 4); //下面的语句输出 Hello!a7
System.out.println("Hello!" + 'a' + 7); //下面的语句输出 104Hello!
System.out.println('a' + 7 + "Hello!");
}
}
上面程序中第一个”3 + 4 + "Hello!"“的表达式,这个表达式先执行”3 + 4“运算,这是执行两个整数之间的加法,得到7,然后进行”7 + "Hello!"“的运算,此时会把7当成字符串进行处理,从而得到7Hello!。
第二个,对于”"Hello!" + 3 + 4“表达式,先进行”"Hello!" + 3“运算,得到一个Hello!3字符串,再和4进行连接运算,4也被转换成字符串进行处理,最后得到Hello!34。
第三个表达式”"Hello!" + 'a' + 7“同第二个类似。
对于最后一个表达式”'a' + 7 + "Hello!"“,先进行”'a' + 7“加法运算,其中'a'自动提升到int类型,编程a对应的ASCⅡ值:97,从”97+7“将得到104,然后进行”104 + "Hello!"“运算,104会自动转换成字符串,将变成两个字符串的连接运算,从而得到104Hello!。
Integer自动装箱的缓存机制
(2016年腾讯实习生招聘笔试题,扩展)下面这段java代码的输出结果是?(不考虑java 1.5之前的老版本,因为老版本不支持自动装箱)
public class IntegerTest {
public static void main(String[] args) {
Integer i1 = 127; // autoboxing
Integer i2 = 127; // autoboxing
System.out.println(i1.equals(i2)); // true
System.out.println(i1 == i2); // true
Integer i3 = 128; // autoboxing
Integer i4 = 128; // autoboxing
System.out.println(i3.equals(i4)); // true
System.out.println(i3 == i4); // false
Integer i5 = new Integer(127);
Integer i6 = new Integer(127);
System.out.println(i5.equals(i6)); // true
System.out.println(i5 == i6); // false
Integer i7 = 127; // autoboxing
Integer i8 = new Integer(127);
System.out.println(i7.equals(i8)); // true
System.out.println(i7 == i8); // false
int i = 127;
System.out.println(i7.equals(i)); // true
System.out.println(i8.equals(i)); // true
System.out.println(i7 == i); // true
System.out.println(i8 == i); // true
}
}
分析:本题的考察点在于Integer类对于[-128 , 127]之间的整数自动装箱缓存的机制,查看Java系统中java.lang.Integer类的源代码,其中有一个叫做IntegerCache的静态内部类如下:
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/ private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[]; static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h; cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
} private IntegerCache() {}
}
从上面的代码可以看出,系统已经把[-128 , 127]之间的256个整数自动装箱成Integer实例,并放入了cache数组中缓存起来。
当把[-128 , 127]之间的同一个整数自动装箱成Integer实例时,永远都是引用cache数组的同一个元素,(i1 == i2)结果为true;
当把一个不在[-128 , 127]范围内的整数自动装箱成Integer实例时,系统总是重新new一个Integer实例,开辟新的内存空间,因此(i3 == i4)、(i5 == i6)、以及(i7 == i8)的结果均为false;
Integer和int进行比较时,Integer会自动拆箱成int类型变成值比较,因此(i7 == i)和(i8 == i)的结果均为true;
Integer类重写了从Object类继承而来的equals方法进行值比较,所以上述equals的结果均为true。
Java小陷阱的更多相关文章
- java常量池中基本数据类型包装类的小陷阱
想必大部分学过java的人都应该做过这种题目: public class Test { public static void main(String[] args) { //第一个字符串 String ...
- T-SQL中的一些小陷阱
1,当心ISNULL函数对你的逻辑引起BUG 有人喜欢或者习惯于(并不代表我推荐,甚至这种写法没有任何好处)用ISNULL处理变量这种方式写查询 比如:select * from TestISNULL ...
- java正则表达式之java小爬虫
这个java小爬虫, 功能很简单,只有一个,抓取网上的邮箱.用到了javaI/O,正则表达式. public static void main(String[] args) throws IOExce ...
- Java小项目--坦克大战(version1.0)
Java小项目--坦克大战<TankWar1.0> 这个小项目主要是练习j2se的基础内容和面向对象的思想.项目实现了基本的简单功能,我方一辆坦克,用上下左右键控制移动方向,按F键为发射炮 ...
- 输出多行字符的一个简单JAVA小程序
public class JAVA { public static void main(String[] args) { System.out.println("-------------- ...
- (10.16)java小作业!
相信大家刚刚学习java多多少少都会写一些java的基础编程来练练手感,我也不例外!今天想和大家分享一下我最近所接触到的比较有趣的java小编程! 已知a已被赋值,b已被赋值,请编写java程序实现a ...
- 浏览器兼容java小程序配置说明
最近在使用的一个web应用系统是内嵌了java小程序,遇到了各种浏览器兼容性问题,现梳理如下: 1.通过以下链接检测当前电脑是否已经安装有java https://java.com/zh_CN/dow ...
- C++ string中的几个小陷阱,你掉进过吗?
C++开发的项目难免会用到STL的string,使用管理都比char数组(指针)方便的多,但在得心应手的使用过程中也要警惕几个小陷阱,避免我们项目出bug却迟迟找不到原因. 1. 结构体中的stri ...
- Python中定义函数时参数有默认值的小陷阱
在定义函数的时候,如果函数的参数有默认值,有两种类型的参数,一种是整数,字符串这种不可变类型,另一种是列表这种可变类型,对于第一种情况没有什么特殊的地方,但是对于可变类型,有一个微妙的小陷阱. 可变类 ...
随机推荐
- css制作三角形
#triangle-up { width: 0; height: 0; border-left: 50px solid transparent; border-right: 50px solid tr ...
- HDU 4054
http://acm.hdu.edu.cn/showproblem.php?pid=4054 模拟题,对一个字符串的每个字符输出16进制表示的数字,每行处理16个字符,后面再把这16个字符输出,大小写 ...
- 机器学习技法-随机森林(Random Forest)
课程地址:https://class.coursera.org/ntumltwo-002/lecture 重要!重要!重要~ 一.随机森林(RF) 1.RF介绍 RF通过Bagging的方式将许多个C ...
- java 中获取文件路径
方案一: 文件目录如下: 配置文件:firehosetos3sample.properties在src目录下面第一层,与包是一层的 在Getpath_ClassLoader.java类中: Syste ...
- 使用批处理文件,自动设置计算机IP地址
WIN7批处理设置IP地址不成功,显示“The filename, directory name, or volume label syntax is incorrect.”错误, 解决方法:将“本地 ...
- 如何在ALV_Grid的函数中定义下拉列表
转自 http://www.cnblogs.com/VerySky/articles/2392262.htmlABAP--如何在ALV_Grid的函数中定义下拉列表 REPORT. ********* ...
- vsftpd搭建及配置参数
一.FTP简介 FTP:File Transger Protocol(文件传输协议) 文件共享服务:工作在应用层 NFS:Network File System(RPC:Remote Procedur ...
- hdu1213 并查集
题意:有 n 个朋友,他们可能相互认识,A 认识 B,B 认识 C,则 ABC 相互认识,现在给出他们的认识情况,相互认识的人坐一桌,否则需要分开坐,问至少需要多少桌. 其实就是问并查集的个数,在初始 ...
- 【BZOJ1011】【HNOI2008】遥远的行星
奇奇怪怪突然出戏的奇葩题 原题: 直线上N颗行星,X=i处有行星i,行星J受到行星I的作用力,当且仅当i<=AJ.此时J受到作用力的大小为 Fi->j=Mi*Mj/(j-i) 其中A为很小 ...
- 关于VC、MFC和ACCESS的一些使用问题
最近在用VC.MFC和ACCESS开发一些小工具. 由于操作系统和开发工具以及数据库版本都升级了,和当年有一些区别了(我这是有多老了--fuck--),遇到一些问题,贴在下面: 1,用什么连接AC ...