0

I have the following code and its throwing StackOverflowException because of nested constructor call, and I know memory gets allocated only when constructor runs successfully.

package interview;

public class StackOverflow {
    int i;
    StackOverflow()
    {
            System.out.println(" i= "+i);
        System.out.println("in Constructor");
        StackOverflow sOf = new StackOverflow();
        sOf.i=5;
        System.out.println(" i= "+i);
    }
    public static void main(String[] args) {
        System.out.println("in main");
        StackOverflow s = new StackOverflow();
        s.i=10;
        System.out.println(" i= "+s.i);
    }

}

So my doubt here is what is happening to the value of 'i' ? Is it getting stored somewhere in stack or heap? In which case the above code can throw the following Exception?

OutOfMemoryException

Sahil Chhabra
  • 10,621
  • 4
  • 63
  • 62
ankit
  • 4,919
  • 7
  • 38
  • 63
  • 1
    http://stackoverflow.com/questions/11435613/whats-the-difference-between-stackoverflowerror-and-outofmemoryerror – Trying Oct 23 '13 at 04:23
  • @ankit - Your question title and the actual question described are totally different. Also, it confuses the answer posters if you change the question once an answer has been posted to your question. Please refrain from doing it. – Rahul Oct 23 '13 at 04:33
  • @R.J thanks for the suggestion I will take care of this. but in initial question also I had mentioned about the value of i – ankit Oct 23 '13 at 04:34
  • 1
    Yeah I saw that, but just that the title made the focus go on `SOE vs OOME` and the last line of your question *in which case it can throw ? OutOfMemoryError*. Your question is good, just that, you need to give appropriate titles and have the description focus on what exactly you want to know. Always remember, good questions fetches good answers! :) – Rahul Oct 23 '13 at 04:37

4 Answers4

2

OutOfMemoryError: Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

StackOverflowError: Thrown when a stack overflow occurs because an application recurses too deeply.

in which case it can throw OutOfMemoryError?

  • Your constructor is recursively calling itself going into more deep, stack overflowed before JVM was out of memory.

    instead of recursion use a for loop to create too much object. You might be able to see the OutOfMemoryError.

My question is what is happening to the value of i( it is getting stored heap or stack):

  • The JVM specification-2.5.2 clearly states that:

    A Java Virtual Machine stack is analogous to the stack of a conventional language such as C: it holds local variables and partial results, and plays a part in method invocation and return.

    As Heap is storage for objects and i is a field member of your StackOverflow class, it gets stored in the Heap

Sage
  • 15,290
  • 3
  • 33
  • 38
  • thats right and I know but my question here is what is happening to the value of I where it is getting stored heap or stack. – ankit Oct 23 '13 at 04:30
  • it is the heap, as it is a member field. – Sage Oct 23 '13 at 04:31
  • @ankit `i` will always be 0 – Trying Oct 23 '13 at 04:34
  • @Trying I know about the value I just want to know its there on stack or heap – ankit Oct 23 '13 at 04:35
  • i have updated the answer, stack is responsible for keeping only local variables as the specification says – Sage Oct 23 '13 at 04:36
  • i is a class variable, so it is getting stored in Heap. And since it is not defined at the time of declaration it will get the default value of int i.e. 0. Your constructor never reaches the line where you are assigning the value 5 to i. So it will always have the value 0. – Sahil Chhabra Oct 23 '13 at 04:44
1

When you start your JVM, some memory is allocated to it from the operating system. The jvm uses this memory for its processing purpuses. JVM uses this memory in a number of ways - like stack and heap.

Whenever a method is called, the data like parameters, the return values and other local variables inside that method is kept on a stack. This stack is created when the method is called and is destroyed when the method completes its execution. If you keep on calling a method from a method , there would be some point at which the bottleneck will occur and it will show you a StackOverFlowError. But in case of heap - the JVM allocates memory to the new object from this heap. If you have references to objects and the free space left in heap is very less it will show you OutOfMemoryError.

shikjohari
  • 2,278
  • 11
  • 23
0

When you start JVM you define how much RAM it can use use for processing. JVM divides this into certain memory locations for its processing purpose, two of those are Stack & Heap

OutOfMemoryError is related to Heap. If you have large objects (or) referenced objects in memeory, then you will see OutofMemoryError.

StackOverflowError is related to stack. All your local variables and methods calls related data will be on stack. For every method call one stack frame will be created and local as well as method call related data will be placed inside the stack frame. Once method execution is completed, stack frame will be removed. ONE WAY to reproduce this is, have infinite loop for method call, you will see stackoverflow error, because stack frame will be populated with method data for every call but it won't be freed (removed).

In your case you are calling the constructer which causing the stack to overflow rather than heap, hence getting the StackOverflowError rather than OutOfMemoryError.

StackOverflow()
    {                        
        StackOverflow sOf = new StackOverflow(); //causing Stack to overflow.**                       
    }

The i's value will always be 0 i.e. the default value.

Please refer this.

Community
  • 1
  • 1
Trying
  • 14,004
  • 9
  • 70
  • 110
0

Whenever you make a call to a function inside another function, the 2nd function comes at the top of the Stack. And since you have made recursive call to your constructor, it keeps on increasing your Stack size because of your new constructors. When there is no space left to create a new constructor entry in the main Stack, JVM throws StackOverflowException.

For OutofMemoryException, you just need to create as many Objects of, as much possible size such that there is no space left in your Heap.

Class variables and Objects are created in Heap and function calls, and local variables are maintained in Stack.

i is a class variable, so it is getting stored in Heap. And since it is not defined at the time of declaration it will get the default value of int i.e. 0. Your constructor never reaches the line where you are assigning the value 5 to i. So, it will always have the value 0.

Sahil Chhabra
  • 10,621
  • 4
  • 63
  • 62