方法内引用的对象是在堆上的是吗?引用的变量在栈是吗?

解决方案 »

  1.   

    对象可能在栈中,比如String
    变量也可能在堆中,下面的例子中,
    数组名dogs是应用变量,存在栈中. dogs[0],dogs[1],dogs[2]也是引用变量,存在堆中。class Dog {
        private static int count = 1;
        private final int id = count++;    public int getId() {
    return id;
        }
    }public class TestDpg {
        public static void display(Dog dog) {
    System.out.println(dog.getId());
        }    public static void main(String[] args) {
    Dog[] dogs = { new Dog(), new Dog(), new Dog() };
    for (int i = 0; i < dogs.length; i++) {
        display(dogs[i]);
    }
        }
    }
      

  2.   

    对象都在堆中,即使是String也是。
    栈中只存放引用和直接常量。
    成员变量是与其对象一起存放在堆中。还有,字符串对象引用的字符串是存放在常量池中,常量池既不属于方法栈,也不属于堆,而在虚拟机另外一块内存中,叫方法区,这块地方用来存放类信息,方法信息以及静态成员属性信息,当然也包括常量池。严格说来常量池属于类信息。
      

  3.   

    还有一个,像int 12这些,范围在-128~127,也是在常量池中。
      

  4.   

    比如Integer i1 = new Integer(43)  
    Integer i2 = new Integer(43)i2.equals(i1)肯定为true。
    i2==i1也为true,因为那些一个字节以内的值都在常量池中