码迷,mamicode.com
首页 > 编程语言 > 详细

java 对象和基本数据类型 “==”区别

时间:2016-02-22 11:55:42      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

“==”比较的是地址,牢记。
1。对象。integer 是对象
Integer i1 = 20;
Integer i2 = 20 ;
System.out.println(i1 == i2); // true
Integer i3 = 200;
Integer i4 = 200 ;
System.out.println(i3 == i4); // false

 

原因:Integer i1 = 20; 其实是一个自动装箱的过程,编译器会自动展开成Integer i = Integer.valueOf(20);详情可以看Integer.valueOf的源代码,可以看到参数的值在IntegerCache.low(默 认-128) 到 IntegerCache.high(默认127)范围内时(比如20),会从IntegerCache.cache中直接取(此处参考Integer的 内部类IntegerCache的源代码,如果不配置的话,默认是cache存储-128到127的Integer),所以取到的都是同一个 Integer的对象,因此相同。而200不在-128到127范围内,所以会new 一个新的Integer,故不相同。
 
2.类型。int 是基本数据类型
 
int i1=20;
int i2=20;
System.out.println(i1==i2);//true
int i3=200;
int i4=200;
System.err.println(i3==i4);//true

原因:i1 开辟了一个内存空间,对于i2来说,jvm先在内存中寻找是否有20的地址,有就给i2赋值,也就是让i2也指向20那块地址。所以返回的是TRUE.

3.

String str1 = "hello";
String str2 = "he" + new String("llo");
System.err.println(str1 == str2);

 返回的是false。

原因:因为str2中的llo是新申请的内存块,而==判断的是对象的地址而非值,所以不一样。如果是String str2 = str1,那么就是true了。

 
 
 
 

java 对象和基本数据类型 “==”区别

标签:

原文地址:http://www.cnblogs.com/PopShow/p/5206504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!