user2860053
user2860053

Reputation:

how to resolve StackOverFlowError?

My Inner and outer class file here:-

package com.demo;

public class Outer {
int outer_x=100;

void test(){
    Inner inner =new Inner();
    inner.display();
}
public class Inner {
void display(){
    Outer ob=new Outer();
    ob.test();

    System.out.println("display: outer_x= "+outer_x);
}
}

}

Another main class acess outer class member :-

package com.demo;

class InnerClassDemo{
    public static void main(String args[]){
        Outer outer=new Outer();
        outer.test();
    }
}

Exception:-

Exception in thread "main" java.lang.StackOverflowError
    at com.demo.Outer.<init>(Outer.java:3)
    at com.demo.Outer$Inner.display(Outer.java:12)
    at com.demo.Outer.test(Outer.java:8)

How can resolve this issue ,pls give me any idea?

Upvotes: 0

Views: 1853

Answers (4)

user2860053
user2860053

Reputation:

I resolved this issue from @rgettman answer modified my Inner and outer class here

package com.demo;
public class Outer {
int outer_x=100;

void test(){
    Inner inner =new Inner();
    inner.display();
}
public class Inner {
void display(){

    System.out.println("display: outer_x= "+outer_x);
}
}

}

Upvotes: 1

erencan
erencan

Reputation: 3763

You get StackOverFlowError, because your call has a infinite method call which always exceeds program stack.

Your test method calls display and display method calls testunconditionaly.

It is the basic requirement to define a base case for recursive methods, so you should define a base case which will return and stop recursive method calls.

See also

Recursion

Upvotes: 0

rgettman
rgettman

Reputation: 178303

Your test method creates an Inner and calls its display() method, which creates an Outer and calls its test method. Nothing in your code stops this from continuing forever, until enough methods have been called to fill up the stack space and a StackOverflowError occurs.

Either don't have test call display, or don't have display call test.

Upvotes: 2

cangrejo
cangrejo

Reputation: 2202

Outer.test calls Inner.display which calls Outer.test which calls Inner.display which calls Outer.test which calls Inner.display which...

This goes on until your program runs out of stack space.

Upvotes: 0

Related Questions