Last active
April 24, 2019 16:53
-
-
Save xuhang57/ea5ce07f87effd8335a0d151d8dd1f84 to your computer and use it in GitHub Desktop.
Stack Memory and Heap Space in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* https://www.baeldung.com/java-stack-heap */ | |
class Person { | |
int pid; | |
String name; | |
// constructor, setter/getters | |
} | |
public class Driver { | |
/** | |
* 1. Upon entering the main() method, a space in stack memory would be created to store primitives | |
* and references of this method. i) the primitive value of integer id. ii) the reference variable | |
* p of type Person will also be created in stack memory which will point to the actual object | |
* in th heap | |
* | |
* 2. The call to the parameterized constructor Person(int, String) from main() will allocate further | |
* memory on top of the previous stack: i) the this object reference of the calling object in the | |
* stack memory. ii) the primitive value id in the stack memory. iii) The reference variable of String | |
* argument personName which will point to the actual string from string pool in heap memory | |
* | |
* 3. This default constructor is further calling setPersonalName() method, for which further allocation | |
* will take place in stack memory on top of previous one. Again, store local variables. | |
* | |
* 4. However, for the newly created object p of type Person, all instance variables will stored in heap memory | |
* | |
*/ | |
public static void main(String[] args) { | |
int id = 23; | |
String pName = "Jon"; // pName reference in Stack, but the String Pool in Heap | |
Person p = null; | |
p = new Person(id, pName); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment