Search code examples
javastringmemory-model

Memory models for strings in Java when one reference variable gets passed in the new Object


In the following code:

String str1= new String("Hello");
String str2= new String(str1);

I was wondering, What gets passed in when I type (str1)? The literal "Hello" or the address in memory of the String object referenced by str1?

In the memory model, Does it mean that the new object contains the address that would point to the object referenced by str1 OR would it contain the literal "Hello" of its own?

Thank You


Solution

  • Basically the address gets passed in, but it's called a "reference" and might actually be a handle or some other number, not literally a memory address. Each new SomeObject generates its own unique reference.

    Inside String, the ctor is smart enough to recognize a different String, and copy the data, the "Hello" part of the string you passed into the ctor. The ctor doesn't try to store a copy of the reference directly.

    Similar question: Is Java pass-by-value or pass-by-reference?