[英]How Memory Has Been Allocated Static variable and Static Block in Java?
如何在 Java 堆棧或堆中分配靜態變量和靜態塊的內存?
class A{
static int a;
static{}
public static void main(String args[]){
A h=new A();
}
}
創建對象時如何為靜態堆棧或堆分配內存。
static
關鍵字在java中主要用於內存管理。 我們可以將static
關鍵字應用於變量、方法、塊和嵌套類。 static
關鍵字屬於類而不是類的實例。
stactic
變量的內存分配僅在類加載到內存中時發生一次。
因此,一旦類加載classloader
加載了classloader
,內存將被分配給整數 a 和靜態塊。
靜態方法(實際上是所有方法)以及靜態變量都存儲在堆的 PermGen 部分中。
可能比對創建它的過程的調用壽命更長的數據通常分配在堆上。 例如 new 創建可以從過程傳遞到過程的對象。 編譯時無法確定堆的大小。 僅通過指針或引用引用,例如 C++ 中的動態對象,Java 中的所有對象
過程的本地名稱在堆棧上分配空間。 編譯時無法確定堆棧的大小。
有關內存管理的更多信息,請參閱以下教程: http : //www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf
在這里,您可以詳細了解分步技術。
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.
}
}
簡而言之,靜態塊、類、變量、方法 - 位於堆內的永久生成區域內。
希望這能澄清大家!!! 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.