日期:2014-05-20  浏览次数:20573 次

java中的数值问题


public class Test {

public static void main(String[] args) {
Integer integer1 = 20;
int int1 = 20;
System.out.println(integer1 == int1);//java中有自动装包拆包,所以20这个数字存储在栈中,是同一个20,所以为true

Integer integer2 = new Integer(20);
int int2 = 20;
System.out.println(integer2 == int2);//但是这里的Integer是new出来的,不应该是存在堆中么?为什么这里还是true?
}
}



一个字符串,String s = "abcd";这个abcd到底存储在哪?String s2 = new String("abcd");这样应该是在堆中new出了一个String对象,s2,s2指向了栈中的字符串常量"abcd"么?

这些问题一直老是不清晰,今天一定要彻彻底底废掉这几个问题!
------解决方案--------------------
1、在判断 integer2 == int2 的时候,因为一边是属于基本型别 int,所以另一边 Integer 会自动拆包,于是变成了 int==int 的比较。

2、s 是存在字符串缓存中的,s2 是新建的对象,不会指向之前创建的任何 "abcd"。
------解决方案--------------------
针对Integer==int这点,其实是这样的,当Integer与int值比较(也就是==)的时候,Integer会自动拆箱成int型,所以是true;http://www.cnblogs.com/liuling/archive/2013/05/05/intAndInteger.html
针对字符串这点,如果使用new来创建一个字符串实例的话,会在堆中创建,如果只是像  String s=“abc”;这样的,虚拟机会在字符串常量池中寻找有没有“abc”对象,如果有,直接将此地址复制给s,如果没有,则会在常量池中创建。http://blog.csdn.net/yuan514168845/article/details/17513437