简体   繁体   中英

How Memory Has Been Allocated Static variable and Static Block in Java?

How Memory has been allocated Static variable and Static Block in Java stack or heap?

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

When create the object how memory allocated for static stack or heap.

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

Memory allocation for stactic variables only happens once when the class is loaded in the memory.

So, here once the class is loaded by the classloader the memory will be allocated for integer a and stacic block.

Static methods (in fact all methods) as well as static variables are stored in the PermGen section of the heap.

Data that may outlive the call to the procedure that created it is usually allocated on a heap. Eg new to create objects that may be passed from procedure to procedure. The size of heap can not be determined at compile time. Referenced only through pointers or references, eg, dynamic objects in C++, all objects in Java

Names local to a procedure are allocated space on a stack. The size of stack can not be determined at compile time.

Please refer the following tutorial for more about memory management : http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf

Here you go for step-step tech in detail..

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.

     }
   }

In short Static Blocks, Class, Vars, Methods - sits inside Permanent-Generation area within heap.

Hope this clarifies everyone!!! Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM