-3

Below is a program given for assignment. Request you to help on the below output getting as "Expected output". It providing error as "Exception in thread "main" java.lang.StackOverflowError".

class A
{
    {
        new B();
    }

    static class B
    {
        {
            new A().new C();
        }
    }

    class C
    {
        {
            System.out.println("Expected output");
        }
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        new A();
    }
}
Robin Green
  • 32,079
  • 16
  • 104
  • 187
Udaya Kumar
  • 29
  • 1
  • 5

2 Answers2

4

You call new A(), which calls new B(), which calls new A() again, which calls new B() again, and it goes on and on until you can't create new objects anymore (thus StackOverflowError).

You should stop creating A() or B() at some point

Cargeh
  • 1,029
  • 9
  • 18
  • Please help on the way to stop creating A() or B() at some point – Udaya Kumar Apr 28 '18 at 11:19
  • 2
    @UdayaKumar it's unclear (not obvious) what you want to achieve with this program :) Why the need for 3 classes and initialization blocks? Are you sure you know what they do? – Cargeh Apr 28 '18 at 11:20
  • first of all thanks for the prompt response. I am new to java. I was just wondered whether I can get the output from program. I am just learning.Thanks Cargeh... – Udaya Kumar Apr 28 '18 at 11:28
  • 1
    @UdayaKumar: You could achieve that by getting rid of your classes and just putting this one line in the `main()` method: `System.out.println("Expected output");` – David Apr 28 '18 at 11:35
  • The teacher wants you to get familiar with anonymous black and static block – Rajat Apr 28 '18 at 11:44
0
class A
{
    {
        new B();
    }

    static class B
    {
       static {
            new A().new C();
        }
    }

    class C
    {
        {
            System.out.println("Expected output");
        }
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        new A();
    }
}

The Anonymous block is executed before any of the constructor static block is executed before loading a static class

Rajat
  • 2,467
  • 2
  • 29
  • 38