首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java中如何分配内存的静态变量和静态块?

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

Stack Overflow用户
提问于 2014-04-09 02:47:17
回答 2查看 3.3K关注 0票数 1

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

代码语言:javascript
复制
  class A{
    static int a; 
    static{}
    public static void main(String args[]){
        A h=new A();
     }
   }

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

EN

回答 2

Stack Overflow用户

发布于 2014-04-09 02:50:21

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

当类加载到内存中时,stactic变量的内存分配只发生一次。

因此,一旦类被classloader加载,内存将被分配给整数a和堆栈。

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

可能比对创建它的过程的调用持续时间更长的数据通常分配在堆上。例如用于创建可以从一个过程传递到另一个过程的对象的new。堆的大小不能在编译时确定。只能通过指针或引用来引用,例如,C++中的动态对象、Java中的所有对象

过程的本地名称被分配给堆栈上的空间。堆栈的大小无法在编译时确定。

有关内存管理的更多信息,请参阅以下教程:http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf

票数 1
EN

Stack Overflow用户

发布于 2020-04-18 10:54:47

在这里,您将详细介绍step-step技术。

代码语言:javascript
复制
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.

     }
   }

简而言之,静态块,类,变量,方法-位于堆中的永久生成区中。

希望这能让大家明白!谢谢!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22945686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档