Asked
Active
Viewed 60 times
-8

user10867746
- 11
- 3
-
1Flagged for closing as it stays unclear what's the issue and what's the question. – dbl Jan 04 '19 at 15:45
-
1Possible duplicate of [java StackOverflowError when local and instance objects creation](https://stackoverflow.com/questions/3679832/java-stackoverflowerror-when-local-and-instance-objects-creation) – Slaw Jan 04 '19 at 15:49
1 Answers
0
Remove the line
Sample obj3 = new Sample();
because that will result in an endless loop (creating an instance of Sample
while during the creation of an instance of Sample
), causing your StackOverflowError
.
And please dont post code as an image.

f1sh
- 11,489
- 3
- 25
- 51
-
Sorry for the inconvenience, I tried to write the code but due to some indentation error, stack overflow was not accepting. I am new to Java. so when I create an object "obj 1" the heap memory and stack memory will be initialized for the instance variable and local variable and class variable will be initialized in method area. So where and how will the above statement for "obj3" creation will be stored or initialized – user10867746 Jan 04 '19 at 16:00
-
1`obj3` is declared as a field (because it't not inside of any method) of `Sample` and will be initialized with an instance of `Sample` when ever the surrounding instance is created. You create an `obj1` in your `main`, which creates an `obj3`, which creates an `obj3`, ... and this goes on until you run out of memory. – f1sh Jan 04 '19 at 16:03
-
Thanks but if its recursive, is it possible to have objects with same name – user10867746 Jan 04 '19 at 16:10
-
1Of course it is, but each new instance of `Sample` creates a new, inner instance of `Sample`. This recursion goes on forever and never stops. – f1sh Jan 04 '19 at 16:20