Thursday 23 May 2019

Is Java primitive data types stored in stack or heap?


Stack is a special region in computer memory, that stores temporary variables like local variables, parameters, function calls etc.,

Heap is a portion of memory where dynamic allocation and de allocations happen. All the Java objects stored in Heap.

In case of primitive data types, primitive variables defined locally (within a function, block) are stored on the stack, where as if a primitive variable defined as part of an object is stored in Heap.

public class Arithmetic {
 private int x; // Stored in Head
 
 public Arithmetic(int x) {
  this.x = x;
 }
 
 public int square() {
  int y = x * x; //y is stored in stack
  return y;
 }
}

In the above example, x is stored in heap, whereas y is stored ins tack


You may like

No comments:

Post a Comment