I have understood from this and this answer, the possible scenarios where your code could get into an infinite loop resulting into stackOverFlowError but I don't understand how the same scenario is getting replicated here,
public class A {
private B b = new B();
@Override
public String toString() {
return "b "+b;
}
}
public class B {
private A a = new A();
@Override
public String toString() {
return "";
}
}
public class StackoverflowErrorTest {
public static void main(String[] args) {
A a = new A();
System.out.println(a);
}
}
This code is generating below stack trace:-
Exception in thread "main" java.lang.StackOverflowError
at stackoverflowerror.B.<init>(B.java:5)
at stackoverflowerror.A.<init>(A.java:5)
.
.
.
As per my understanding, When I am printing object 'a' in the main method, it will invoke the toString method of A class, in that method I am returning the object of B class which would implicitly call the toString method of B class. Now, in the toString method of B class, all I am returning is an empty string. Then how and where is the scope of infinite loop coming into picture here. Please explain.