常量池在方法区中,和堆不是相同的概念。不要把常量池和堆混起来。
按照Inside the java virtual machine这本书上的说法,static的数据放在方法区中。

解决方案 »

  1.   

    int i=100; 
    这中情况i是当作一个立即数压入栈里的。
    对于在short类型表示之外的int数,放在常量池中,需要的时候放到栈里。
    举个例子:public class Test{
        public static void main(String []args){
            int i=1;
            int j=18;
            int k=128;
            int kk=32768;
            int kk2=32768;
        }
    }察看其class文件Compiled from "Test.java"
    public class Test extends java.lang.Object
      SourceFile: "Test.java"
      minor version: 0
      major version: 49
      Constant pool:  //下面是常量池里的内容
    const #1 = Method #4.#13; //  java/lang/Object."<init>":()V
    const #2 = int 32768;  //这个数在常量池中
    const #3 = class #14; //  Test
    const #4 = class #15; //  java/lang/Object
    const #5 = Asciz <init>;
    const #6 = Asciz ()V;
    const #7 = Asciz Code;
    const #8 = Asciz LineNumberTable;
    const #9 = Asciz main;
    const #10 = Asciz ([Ljava/lang/String;)V;
    const #11 = Asciz SourceFile;
    const #12 = Asciz Test.java;
    const #13 = NameAndType #5:#6;//  "<init>":()V
    const #14 = Asciz Test;
    const #15 = Asciz java/lang/Object;{
    public Test();
      Code:
       Stack=1, Locals=1, Args_size=1
       0: aload_0
       1: invokespecial #1; //Method java/lang/Object."<init>":()V
       4: return
      LineNumberTable: 
       line 1: 0public static void main(java.lang.String[]);
      Code:
       Stack=1, Locals=6, Args_size=1
       0: iconst_1   //常数1的处理
       1: istore_1
       2: bipush 18   //b开头可以理解为byte操作
       4: istore_2
       5: sipush 128    //s开头可以理解为short操作
       8: istore_3  
       9: ldc #2; //int 32768  后面这两个都是从常量池中取数,都是从#2取
       11: istore 4
       13: ldc #2; //int 32768
       15: istore 5
       17: return
      LineNumberTable: 
       line 3: 0
       line 4: 2
       line 5: 5
       line 6: 9
       line 7: 13
       line 8: 17}
      

  2.   

    常量池应当上放在类对象的存储区域,我记得原始类型好像是存在栈中,而从Object对象派生类的对象是放在推中的,不知道对不对
      

  3.   

    常量池放这些类型Each item in the constant_pool table must begin with a 1-byte tag indicating the kind of cp_info entry. The contents of the info array vary with the value of tag. The valid tags and their values are listed in Table 4.3. Each tag byte must be followed by two or more bytes giving information about the specific constant. The format of the additional information varies with the tag value.
    Constant Type  Value  
    CONSTANT_Class  7  
    CONSTANT_Fieldref  9  
    CONSTANT_Methodref  10  
    CONSTANT_InterfaceMethodref  11  
    CONSTANT_String  8  
    CONSTANT_Integer  3  
    CONSTANT_Float  4  
    CONSTANT_Long  5  
    CONSTANT_Double  6  
    CONSTANT_NameAndType  12  
    CONSTANT_Utf8  1  
    其中Integer,Float,Double,Long存放的就是基本类型的常数字面量。基本类型的变量是在栈里。
      

  4.   

    java的内存划分为这几部分:
    Runtime Data Areas 
    1 The pc Register 
    2 Java Virtual Machine Stacks 
    3 Heap 
    4 Method Area 
    5 Runtime Constant Pool 
    6 Native Method Stacks