+ 7
Why StackOverflow Error ? [Solved]
This is simple java program. In this program i just created two objects and nothing else. Anyone know why this error is comming. https://code.sololearn.com/c14nDb01b6M2/?ref=app
24 Antworten
+ 5
P Jain you meant final keyword creating issue
as per your last statement
+ 5
P Jain 😂 ok update
+ 4
You are making a new object of a class that's constructor also makes a new object of itself and that further makes new object and so on!
Again again and again!
So we are making unlimited number of objects of this class!
You can add a static variable that is increased when an object is made (i.e. constructor) and put an if statement (or a base case) to prevent this Error!
+ 4
Namit Jain What do you want to explain in this code.
+ 4
Namit Jain we can put in block.
If you heard about static and instance block.😅
And I'm not going to perform explicitly recursion
+ 3
P∆WAN M∆URY∆ Before calling constructor it call x1=new Program() ;
This it self calls same class infinitely...
+ 3
Namit Jain which line creating issue?
+ 3
Namit Jain if I will comment line 10 will it give me error ?
+ 3
P∆WAN M∆URY∆ no
+ 3
Namit Jain In this program you are explicitly creating a recursion and break it.
In my question I didn't use this.
+ 3
P∆WAN M∆URY∆
You cannot put an if statement outside a method 😏🤔
So, how will you stop it without if statement 😑
+ 3
P∆WAN M∆URY∆ yaa! Block is necessary 🙃
But i don't think we can declare variables here
+ 3
The most simple explanation here(For those who not understand stack and heap) :
Basically you're initialising an object of the same class as a member variable. This causes the JVM to find the constructor of the Program which has not been invoked upon yet(because the JVM always inits the members first) so the constructor which is been called makes another call to the constructor and which again makes the same thing... Goes on... Results into Stack Overflow.
Basically you can't create a final object of the same class as a member variable(because you'll have to initialize it either in class block or constructor block which'll cause Stack Overflow). you also can't initialize a normal member(in class or constructor block).
+ 3
P∆WAN M∆URY∆ no I meant that object as a member variable initialisation is the cause of the error.
Oops looked up now ... 😂😂😂 By mistake final was typed... Wait I'll correct that.
+ 3
P∆WAN M∆URY∆ corrected 👍
+ 2
public class Program
{
// final Program x1 = new Program();
Program() {
System.out.println("stack over?");
}
public static void main(String[] args) {
Program x1 = new Program();
}
}
P∆WAN M∆URY∆ Before calling constructor it call x1=new Program() ;
This it self calls same class infinitely.....
+ 2
P∆WAN M∆URY∆ that there should be a limit!
Like here there is a limit of 50
The class should not make its instance if it exceeds the provided limit (50)
+ 1
P∆WAN M∆URY∆ line 3
+ 1
P∆WAN M∆URY∆
This will help you!
https://code.sololearn.com/cIh2UHxyrrzt/?ref=app