Java String.concat()方法示例

Java String.concat()方法示例

原文: https://howtodoinjava.com/java/string/java-string-concat-method-example/

Java String.concat()方法将方法参数字符串连接到字符串对象的末尾。

1. String.concat(String str)方法

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

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);
}

2. Java String.concat示例

Java 程序将连接两个字符串以产生组合的字符串。 我们可以传递空字符串作为方法参数。 在这种情况下,方法将返回原始字符串。

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

程序输出。

Hello world

3. 不允许为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)

学习愉快!

参考文献:

Java String文档