• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static variable and Memory  RSS feed

 
AmitVijay AVKulkarni
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have declared static variable i.e. static int variable , is it stored on Heap or Stack?
E.g.

public class TestStr
{
static int i = 0;

public static void main(String args[])
{
i = 1;
System.out.println(i);
}
}
 
Nischal Tanna
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Primitives on Stack and Objects on Heap (irrespective of static behaviour)
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I beg to differ. The stack is reserved for local variables in methods (both references and primitives, but not objects). Each thread gets its own stack, and stack frames are created and destroyed as methods begin and end. Anything stored in a stack is not accessible to other threads.

Static variables are stored on the heap along with all objects, but I cannot tell you precisely how. My guess is that each Class instance has a JVM-private reference an object holding its set of static fields.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!