Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.concat(String)

In Java SE 21, `String.concat(String)` appends another string. If the argument is empty, it returns the original object.

Version: Java SE 21

Syntax

public String concat(String str)

String.concat(String) appends its argument to the receiver. Strings are immutable, and an empty argument returns the receiver itself. A null argument causes NullPointerException. In contrast, string concatenation with + converts a null reference to the text "null".

The example calls concat through a method handle. In the lookup for concat, MethodType.methodType(String.class, String.class) specifies the return type first and the declared parameter type second. The handle itself takes the receiver first and the string to append second. The (String) cast gives the invokeExact call site the matching return type.

Examples

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class Main {
    public static void main(String[] args) throws Throwable {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle concat = lookup.findVirtual(
                String.class, "concat", MethodType.methodType(String.class, String.class));
        MethodHandle length = lookup.findVirtual(
                String.class, "length", MethodType.methodType(int.class));

        String prefix = "A";
        String joined = (String) concat.invokeExact(prefix, "\uD83D\uDE00");
        int units = (int) length.invokeExact(joined);
        String unchanged = (String) concat.invokeExact(prefix, "");

        System.out.println(units);
        System.out.println(unchanged == prefix);
    }
}

Result

3
true

The example appends U+1F600 to `A`. The `length()` call only measures the result: `A` takes one UTF-16 code unit and the emoji takes two, so the first line is `3`. The second line is `true`: after appending an empty string, `==` confirms that `concat` returned the original object.

Related lessons

  • Java · Lesson 56 · Advanced · Version: 2

Sources