I tried to search the answer on google but didn't find. Why below program is giving StackOverflowError
.
public class HelloWorld {
private HelloWorld obj = new HelloWorld(); // (HelloWorld.java:2)
public static void main(String args[]) {
HelloWorld obj = new HelloWorld();
obj.printHello();
}
private void printHello(){
System.out.println("Hello world");
}
}
Output:
Exception in thread "main" java.lang.StackOverflowError
at HelloWorld.<init>(HelloWorld.java:2)
at HelloWorld.<init>(HelloWorld.java:2)
....................
If I comment the instance variable obj
, then program prints "Hello world" and there is no error.
See below:
public class HelloWorld {
// private HelloWorld obj = new HelloWorld();
public static void main(String args[]) {
HelloWorld obj = new HelloWorld();
obj.printHello();
}
private void printHello(){
System.out.println("Hello world");
}
}
Output:
Hello world
When creating a new instance of a class, like you are doing in the main method:
HelloWorld obj = new HelloWorld();
That class's instance variables' variable initialisers get executed, which in the case of HelloWorld
, is this line here:
private HelloWorld obj = new HelloWorld(); // (HelloWorld.java:2)
That line creates another HelloWorld
instance, which causes that same line to run again. To run that line again, another instance would need to be created, which means that same line has to run again, and again, and so on...
Another way to think of this is to imagine HelloWorld
to have a constructor like this:
class HelloWorld {
private HelloWorld obj;
public HelloWorld() {
obj = new HelloWorld();
}
}
You should clearly see the infinite recursion happening.