1

Why this code doesn't execute fine. It throws java.lang.StackOverflowError. I want to know the behavior of the class.

public class A {
A a = new A();
public static void main(String[] args) {
    A a = new A();
    System.out.println("i'm done!");
}}

2 Answers2

3

Your creating an instance variable a of A and initializing it with every call to the constructor. So it keeps going like a infinite loop

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

The issue you are facing is that you are redeclaring the class with the default/blank constructor on the second line, causing an infinite loop and thus a StackOverflowError.

Remove to match:

public class A {
public static void main(String[] args) {
    A a = new A();
    System.out.println("i'm done!");
}}
Sean Perkins
  • 541
  • 3
  • 10