Java 字符串拼接 String concat() 示例代码

Java 的 concat() 方法将传入的字符串参数,拼接到原来字符串对象的末尾。

String concat() 方法

在内部,Java 使用字符串对象和参数字符串的长度创建一个新的字符数组,并将两个字符串中的所有内容复制到这个新数组中。最后,通过String字符数组构造器转换为字符串对象。

public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    int len = value.length;
    char buf[] = Arrays.copyOf(value, len + otherLen);
    str.getChars(buf, len);
    return new String(buf, true);
}

Java String concat 示例代码

Java 程序拼接两个字符串以生成新的组合字符串。

我们可以传递一个空字符串作为方法参数,在这种情况下,方法将返回原始字符串。

public class StringExample {
    public static void main(String[] args) {
        System.out.println("Hello".concat(" world"));
        System.out.println("Hello".concat(""));
    }
}
Hello world
Hello

‘null’ 是不允许的

参数’null’是不允许的,拼接它将抛出空指针异常NullPointerException

public class StringExample {
    public static void main(String[] args) {
        System.out.println("Hello".concat( null ));
    }
}
Exception in thread “main” java.lang.NullPointerException
at java.lang.String.concat(String.java:2014)
at com.StringExample.main(StringExample.java:9)
标签: