Reputation: 23
I have read that only primitives are stored in Stack memory and objects are stored in Heap memory. In the following program I am recursively calling a method to check the maximum stack size before stackoverflow error occurs.
public class MaxStackSize {
static int i =0;
public static void main(String[] args) {
method1();
}
public static void method1()
{
i++;
System.out.println(i);
method1();
}
}
Here the max output for 'i' is 53481.
If I add HashSet object to the method and populate it:
public class MaxStackSize {
static int i =0;
public static void main(String[] args) {
method1();
}
public static void method1()
{
HashSet<String> set = new HashSet<String>();
set.add("one");
set.add("two");
set.add("three");
set.add("four");
set.add("five");
set.add("six");
set.add("seven");
set.add("eight");
set.add("nine");
i++;
System.out.println(i);
method1();
}
}
The max output for 'i' is 25403.
For both the cases VM arg is -Xss5m.
If only primitives are stored on stack why does the stacksize decrease when object of HashSet is created.
Upvotes: 2
Views: 304
Reputation: 86774
Primitives are stored on the stack. So are local variables which are object references. The HashSet
you instantiate goes on the heap but the reference to each HashSet
, variable set
, goes on the stack.
Upvotes: 2