Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

The String(String) copy constructor

The `String(String)` constructor creates a distinct object with the same text. Use `==` to compare references and `equals` to compare string contents.

Version: Java SE 21

Syntax

public String(String original)

String copy = new String(original);

In Java SE 21, String(String) is the java.lang.String constructor overload that takes an existing string. Each successful evaluation of new String(original) creates a distinct object with the same character sequence as original. Distinct object identity does not guarantee separate storage for the characters. If the String argument is null, the constructor throws NullPointerException.

Every occurrence of the literal "Alpha" refers to the same interned object, but two evaluations of new String("Alpha") produce two objects distinct from each other and from the literal's object. For references, == tests whether both refer to the same object or both are null. For a non-null string s, s.equals(t) is true when t is a string with the same character sequence, with case taken into account.

String alias = original; copies the reference without creating a new object. Strings are immutable, so reuse the existing reference when you just need to pass the text along. Use the copy constructor only when you need a distinct object identity.

Examples

public class StringCopyDemo {
    public static void main(String[] args) {
        String literal = "Alpha";
        String alias = literal;
        String first = new String("Alpha");
        String second = new String("Alpha");

        System.out.println(literal == "Alpha");
        System.out.println(alias == literal);
        System.out.println(first == literal);
        System.out.println(first == second);
        System.out.println(first.equals(second));
    }
}

Result

true
true
false
false
true

The first two `true` results show literal sharing and reference assignment. The two `false` results show that the first copy is a different object from both the literal and the second copy. The final `true` confirms that the copies contain the same text.

Related lessons

  • Java · Lesson 17 · Advanced · Version: 2

Sources