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

“==”比较的是地址,牢记。
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.java

3.jvm

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

 返回的是false。spa

缘由:由于str2中的llo是新申请的内存块,而==判断的是对象的地址而非值,因此不同。若是是String str2 = str1,那么就是true了。对象

相关文章
相关标签/搜索