Java Memory Structure

types of memory area

memory21

Static memory (Method area)

  • Method information and Field information.
  • Global constants and other data generated by the compiler(e.g. info to support garbage collection) are allocated static storage.
  • Static variables are bound to memory cells before execution begins and remains bound to the same memory cell throughout execution. E.g., static variables.

Stack

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

Heap

  • Data that may outlive the call to the procedure that created it is usually allocated on a heap. E.g. 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, e.g., dynamic objects in C++, all objects in Java
  • Garbage collection cleans up data(not using) on heap.

 

Example

class Point {
   int x, y;

   void move(int x, int y) {
      this.x = x;
      this.y = y;
   }

   int getX() {
      return x;
   }

   int getY() {
      return y;
   }

   void setX(int x) {
      this.x = x;
   }

   void setY(int y) {
      this.y = y;
   }

   void draw() {
      System.out.println("Point(" + x + ", " + y + ")");
   }
}

class PointTest {
   public static void main(String args[]) {
      Point p1, p2 = null;

      p1 = new Point();
      p1.move(4, 4);
      // Point 1
      p2 = new Point();
      p2.move(2, 4);

      // Point 2
   }
}

[ PointTest class loaded ]

m1

 

[ JVM calls Main method ]

m2

 

[ At Point 1 in Main method ]

m3

 

 [ At Point 2 in Main method ]

m4

 

Leave A Comment

Your email address will not be published. Required fields are marked *