Java中如何分配静态变量和静态块的内存?

Java中如何分配静态变量和静态块的内存?,java,static,Java,Static,如何在Java堆栈或堆中分配静态变量和静态块的内存 class A{ static int a; static{} public static void main(String args[]){ A h=new A(); } } 创建对象时,如何为静态堆栈或堆分配内存。java中的static关键字主要用于内存管理。我们可以使用变量、方法、块和嵌套类应用static关键字。static关键字属于类而不是类的实例。 stactic变量

如何在Java堆栈或堆中分配静态变量和静态块的内存

  class A{
    static int a; 
    static{}
    public static void main(String args[]){
        A h=new A();
     }
   }

创建对象时,如何为静态堆栈或堆分配内存。

java中的
static
关键字主要用于内存管理。我们可以使用变量、方法、块和嵌套类应用
static
关键字。
static
关键字属于类而不是类的实例。

stactic
变量的内存分配仅在类加载到内存中时发生一次。

因此,在这里,一旦类被
类加载器加载,内存将分配给整数a和stacic块

静态方法(实际上是所有方法)以及静态变量都存储在堆的PermGen部分

通常在堆上分配可能比创建它的过程的调用寿命长的数据。例如,新建以创建可从一个过程传递到另一个过程的对象。 在编译时无法确定堆的大小。仅通过指针或引用引用,例如C++中的动态对象,java

中的所有对象 过程的本地名称在堆栈上分配空间。堆栈的大小不能在编译时确定


有关内存管理的更多信息,请参阅以下教程:

这里详细介绍步骤技术

class A{
    static int a; // goes to method area or Permanent-Generation (which is special mem area within Heap)

    static{} // goes to method area or Permanent-Generation (which is special mem area within Heap)

    public static void main(String args[]){ // goes to method area or Permanent-Generation (which is special mem area within Heap)

        A h=new A(); // 1.using the "new" keyword, an object is created in 
                          Heap
                     // 2. using the constructor A(), the memory has been allocated to the newly created object. This is called object instantiation, based on the variables and methods inside this A class.

                     //3. object ref var "h" will be created in stack

                     //4. using = operator, the memory address of newly created object will be assigned to the object ref h which sits inside the stack.

     }
   }
总之 静态块、类、变量、方法-位于堆中的永久生成区域内


希望这能澄清大家!!!谢谢

我想知道stack或heapi只想知道stack或heapok,但当创建对象时,对象的内存存储在堆中。静态不是类或对象的一部分堆的PermGen部分是什么。检查