Wednesday, November 29, 2006
StackOverflowError When Instantiating A Class
Try out this small piece of code and you can see JVM reports StackOverflowError.
We are trying to instantiate FirstClass object inside main function, FirstClass constructor tries to instantiate SecondClass object and SecondClass constructor tries to instantiate FirstClass object which ends up in a busy endless situation and hence StackOverflows.
Although this is not a common situation of programming, such mistakes or piece of code will be hard to figure out especially when writing Web Application where things are little hard to debug.
If you like to look at the source of this example, check out here.
public class FirstClass {
public FirstClass() {
SecondClass secondClass = new SecondClass();
}
public static void main(String[] args) {
/* Instanstiating FirstClass ends with StackOverflowError */
FirstClass firstClassInstance = new FirstClass();
}
}
public class SecondClass {
public SecondClass() {
FirstClass firstClassInstance = new FirstClass();
}
}
We are trying to instantiate FirstClass object inside main function, FirstClass constructor tries to instantiate SecondClass object and SecondClass constructor tries to instantiate FirstClass object which ends up in a busy endless situation and hence StackOverflows.
Although this is not a common situation of programming, such mistakes or piece of code will be hard to figure out especially when writing Web Application where things are little hard to debug.
If you like to look at the source of this example, check out here.