javastringjvmcloningshallow-copy

What happens to Strings when object is cloned in Java?


By default Java does Shallow Cloning, if an object is cloned and it has a String like this String s = new String("Hi"); then the cloned object will point to a new String object or it will have a reference to the previous object?

The question here is that does Java treat Strings different when cloning and creates a new object of it or not??


Solution

  • new always creates new String object

    1. Every time new is used to create a String, it will create a new object
    2. The references pointing to Strings created by new can be interned to assign to an existing entry in String pool or creates new entry if it does not exist.

    clone

    1. In case of clone, it all depends on the implementation of clone method
    2. If the clone is done as super.clone without any additional code, then all the references are copied (assuming super is Object)
    3. So the String references inside the cloned object will share the existing String objects pointed by original object