1

I have below code:

ClassA.java

public class ClassA {
    static boolean isDone = false;
    public static void main(String[] args) {
        System.out.println("In class A.");
        if (!isDone) {
            new ClassB();
            isDone = true;
        }
    }
}

ClassB.java

public class ClassB {
    ClassB () {
        ClassA.main(null);
    }
}

When running the program, I'm getting following output:

In class A.
In class A.
Exception in thread "main" java.lang.StackOverflowError
    at sun.nio.cs.SingleByte.withResult(Unknown Source)
    at sun.nio.cs.SingleByte.access$000(Unknown Source)
    at sun.nio.cs.SingleByte$Encoder.encodeArrayLoop(Unknown Source)
    at sun.nio.cs.SingleByte$Encoder.encodeLoop(Unknown Source)
    at java.nio.charset.CharsetEncoder.encode(Unknown Source)
    at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)

It is printing "In class A." as expected, but why I'm getting stack over flow error?

2 Answers 2

5

You are setting the flag isDone after calling ClassB(). So there is an infinite recursive call happening, which leads to StackOverFlowError when memory is reached.

Set the flag (isDone), before calling ClassB();.

As shown below:

if (!isDone) {
    isDone = true;
    new ClassB();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Logical mistake. Thanks :)
2

You have an infinite method call chain in your code that is causing the StackOverflowError. This is because you are calling the main method of ClassA from the constructor of ClassB. The if block in your main method will never finishing. The logical error in your code is the setting of flag(isDone) after the creation of ClassB instance instead of doing it before that.

Try changing the if block from

 if (!isDone) {
         new ClassB();
         isDone = true;
  }

to

 if (!isDone) {
         isDone = true;
         new ClassB();
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.