2

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??

Wilfred Almeida
  • 601
  • 8
  • 15
  • I think you'll have to be more specific about your terminology. "Shallow cloning" is like an oxymoron because a "shallow copy" and a "clone" are opposites. And the word clone in Java is also used to describe the `clone()` method (which should generally be avoided). Regarding `new String()`, the `new` keyword *always* gives you a newly allocated object. – Tenfour04 Feb 20 '21 at 02:59

1 Answers1

2

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
Thiyanesh
  • 2,360
  • 1
  • 4
  • 11