【面试】int、integer、String

来源:互联网 发布:怎样开淘宝店教程视频 编辑:程序博客网 时间:2024/06/06 13:11

       昨天面试被问到了一个基础的题目,来总结一下:

               
Integer a=-300;
Integer b=-300;
if (a==b) {
System.out.println("a和b等于");
}else {
System.out.println("a和b不等于");
}


 结果:a和b不等于。


 因为java在编译integer的时候,会翻译成integer.valueOf(-300),其中valueof的源码如下:


1 public static Integer valueOf(int i) {2         assert IntegerCache.high >= 127;3         if (i >= IntegerCache.low && i <= IntegerCache.high)4             return IntegerCache.cache[i + (-IntegerCache.low)];5         return new Integer(i);6     }

    从上面我们可以看到,对于-128到127之间的数,会进行缓冲。也就是数据直接在缓冲中取出来的,所以会相等。但是超过这个范围,数据就会重新申请内存地址,就出出现不相等的情况。



int c=128;
int d=128;
if (c==d) {
System.out.println("c和d等于");
}else {
System.out.println("c和d不等于");
}


 结果:c和d等于

 int的取值范围为:2147483648~2147483647,所以是相等的。



Integer q=1;
Integer p=1;
if (q==p) {
System.out.println("q和p等于");
}else {
System.out.println("q和p不等于");
}


结果:q和p等于,原因同第一个


Integer l=128;

int  k=128;
if (l==k) {
System.out.println("l和k等于");
}else {
System.out.println("l和k不等于");
}
    


 结果:l和k等于,int类型和integer类型进行比较,都是true,因为会把integer自动拆箱为int再去比较。

  

String e="aa";
String f="bb";
String m="aa"+"bb";
if (m==e+f) {
System.out.println("e+f等于m");
}else {
System.out.println("e+f不等于m");
}


 结果:e+f不等于m

int和integer的不同之处:

  1、int是基本类型,初始值为0

2、integer是包装类型,初始值为null

3、他们的装箱和拆箱的区别,以及他们的范围区别。同以上原因

原创粉丝点击