Explain an Object's Lifecycle (creation, "dereference by reassignment" and garbage collection)
- println() -> when this finish it will be removed first
Cedric Bosch wrote:I hope it can help others and myself if I understood something wrong and someone corrects me.
Cedric Bosch wrote:**1. The stack**:
Cedric Bosch wrote:When an object is created in the a method its value is placed in the stack along side with the method. What is the value of the object ? The reference address of the object data which is in ... the heap !
Cedric Bosch wrote:The thing to note here is that the value of a primitive is the data it contains, while the value of an object is a reference to the data object in the heap memory.
Cedric Bosch wrote:When a method leaves the stack, the objects associated with it are not referenced anymore by anything.
Cedric Bosch wrote:Here the reference to the data of animal is lost before the end of the method. Therefor the garbage collector can potentially remove the data from the heap before the end of the method.
Cedric Bosch wrote:Strings are a bit special because the JVM reserves memory for them in the heap as a pool of strings to be more efficient. What that means is that two strings will reference to the same data in the heap string pool.
Cedric Bosch wrote:However when creating a string with the new keyword, the string is NOT placed in the string pool. Ence why s2 != s3. If we want to place a string in the string pool we have to internalize it. s3 = s3.intern(). Then s2 == s3.
Cedric Bosch wrote:I'm 100% sure I've had experience where I initialized two strings with someString = "a" and anotherString ="a" but both weren't equal. So someString != anotherString. I can't reproduce it however. Where can this happen ?
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koophttps://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton