class Test
{
int y=10; // defined as part of the class
Test obj1 =new Test();
public void function1(){
int x = 5; // defined locally
Test obj2=new Test();
}
public static void main(String[] args)
{
Test obj = new Test();
}
}
we already know the varibale "y" will gon heap and variable x will go on stack But my question is where will the reference variable "obj" which is a reference to test class be sved? on heap or stack? Also where will the reference variables "obj1" and "obj2" be saved on stack or heap? Ofcourse the object goes to heap but what about reference variables when declared inside function it goes to stack but what about when declared outside function?Confused.Please Help.
The value of obj1
(the reference) is itself part of an instance of Test
which was allocated on the heap. The value pointed to by obj1
is a different instance of Test
, which is also on the heap.
The only things on the stack are parameters to methods and variables declared inside methods.
Note that your first invocation of new Test()
will fail due to the recursive infinite loop you've set up. Each contruction of a new Test
require the construction of an additional Test
, ad infinitum. You'll probably get a StackOverflowError, as method invocations stake up stack space even with no parameters and local variables.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments