简体   繁体   中英

where static objects are stored in java

I'm reading a book "Thinking in Java" which says objects are stored on heap and static variable on stored on some fixed location say static storage so that they can be available for entire time program is running.

class Myclass{

static int x =0;        //stored on static storage
Myclass obj = new Myclass(); //stored on heap

}

Although making a object, static will not be a good idea as far as OOPS is concerned. Putting this aside for a while. there comes my questions that

  1. where does object which is declared static is stored.
  2. how does JVM does instantiation in this case.
    class Myclass { static Myclass obj = new Myclass(); //no man's land }

All static content will be created on class load/initiation and stored in special location (most probably part of perm gen, differs based on implementation).

For second example, When your Myclass is loaded, it's static content will be created/instantiated.

This tutorial may give you high level overview.

Static is a special memory location to the program. So the program could easily access it. Only one such location available for the program to run. And it's the place where static content is created. The JVM instantiates objects on the heap. But if you make a static reference to the object then it placed in the static memory place.

static variables are stored on method area.
method area is part of non-heap memory . It stores per-class structures, code for methods and constructors. Per-class structure means runtime constants and static fields .
堆内存,非堆内存和方法区域是内存和JVM的主要术语。

It depends on JVM implementation. In your example the variable is initialized to a primitive value and so it will be stored in metaspace(native memory, offheap). In case you initialized it with new ObjectClassSmthng() the object will be stored on heap and x variable (which is a reference) would be stored in metaspace.

This is true for HotSpot JDK 8.

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