Monday 4 November 2019

java - Where is allocated variable reference, in stack or in the heap?



I have a question



What happend when I declare a variable inside a method, for example.




void myMethod() {

Ship myShip = new Ship();
}


Where is allocated myShip reference, in stack or in the heap ?



I think in stack but I'm confused because I was reading in J2ME Game Programming book
"Java classes are instantiated onto the Java heap"



All java clases ?




Thanks in advance


Answer



myShip is a reference to a Ship object, myShip is on the method call stack, which is referred to as "the stack". When a method is called a block of memory is pushed onto the top the stack, that memory block has space for all primitives (int, float, boolean etc) and object references of the method, which includes the method parameters. The heap is where the memory for the actual objects is allocated.



So myShip is on the stack and the Ship object is on the heap.



Note each thread has its own stack but share the heap.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...