Where static objects are stored in java

I am reading the book “Thinking in Java,” which says objects are stored in the heap and static variable when stored in some fixed place, say static storage, so that they can be accessed for the entire time program.

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

Although creating an object statically would not be a good idea regarding OOPS. Set it aside for a while. my questions arise that

  • where the object declared as static is stored.
  • how the JVM creates an instance in this case.
    class Myclass { static Myclass obj = new Myclass(); //no man land }
+4
source share
4 answers

All static content will be created in the loading / initialization of the class and stored in a special place (most likely, this is part of perm gen, differs based on implementation).

In the second example, when your Myclass , static content will be created / created.

This tutorial can give you a high level overview.

+4
source

Static is a special memory location for a program. Thus, the program can easily access it. Only one such place is available for launching the program. And this is the place where static content is created. The JVM creates objects on the heap. But if you statically refer to an object, then it is placed in the place of static memory.

+1
source
Static Variables

stored in the area .
The method area is part of memory without memory . It stores the structures of each class, code for methods and constructors. The Per-class structure means run-time constants and static fields .
heap memory, non-heap memory and method area are the main jargon when it comes to memory and JVM.

0
source

It depends on the implementation of the JVM. In your example, the variable is initialized with a primitive value, and therefore it will be saved in metaspace (native memnory, offheap). If you initialized it using the new ObjectClassSmthng (), the object will be stored on the heap, and the variable x (which is the link) will be stored in metaspace.

This is true for HotSpot JDK 8

0
source

Source: https://habr.com/ru/post/1435549/


All Articles