Java String Copy With Examples

Sometime back I was asked how to copy a String in java. As we know that String is an immutable object, so we can just assign one string to another for copying it. If the original string value will change, it will not change the value of new String because of immutability.

Java String Copy

Here is a short java String copy program to show this behavior.

Note that we can perform direct assignment of one variable to another for any immutable object. It’s not limited to just String objects.

However, if you want to copy a mutable object to another variable, you should perform deep copy.

Java String Copy Alternate Methods

There are few functions too that can be used to copy string. However it’s not practical to use them when you can safely copy string using assignment operator.

  1. Using String.valueOf() method
  2. Using String.copyValueOf() method, a total overkill but you can do it.

If you want to copy part of string to another string, then valueOf and copyValueOf methods are useful.

By admin

Leave a Reply

%d bloggers like this: