Java中的String类提供了一个concat()方法,该方法允许你将指定的字符串附加到当前字符串的末尾。
下面是关于concat()方法的详细介绍:
方法声明
public String concat(String str):
这个方法接受一个字符串作为参数,并将其附加到当前字符串的末尾。
功能描述
concat()方法接收一个字符串作为参数,并将其添加到调用该方法的字符串的后面。
返回值
该方法返回一个新的String对象,在这个新对象中包含了原字符串和附加的字符串的组合。
示例代码
下面是一个使用concat()方法的示例:
public class Codekru {
public static void main(String[] args) {
String s1 = "hello";
System.out.println("Before using concat() method, s1 = " + s1);
s1 = s1.concat(" codekru");
System.out.println("After using concat() method, s1 = " + s1);
}
}
输出结果为:
Before using concat() method, s1 = hello After using concat() method, s1 = hello codekru
关于concat()方法的几点说明
当使用concat()方法时,如果传入的字符串为空(“”),则方法会返回原来的字符串对象的引用;
否则,它会返回一个新的字符串对象,该对象是原字符串和附加字符串的组合。
下面的代码进一步说明了这一点:
public class Codekru {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "";
String s3 = " codekru";
String s4 = s1.concat(s2);
String s5 = s1.concat(s3);
if (s1 == s4) {
System.out.println("s1 and s4 both referring to the same object");
} else {
System.out.println("s1 and s4 referring to the different objects");
}
if (s1 == s5) {
System.out.println("s1 and s5 both referring to the same object");
} else {
System.out.println("s1 and s5 referring to the different objects");
}
}
}
输出结果为:
s1 and s4 both referring to the same object s1 and s5 referring to the different objects
从上面的输出可以看出,s1和s4都指向了同一个对象,而s1和s5则指向不同的对象。
因此,每次使用concat()方法时,如果附加的字符串不是空字符串,则会创建一个新的对象。
concat()方法的实现
concat()方法的内部实现如下所示:
public String concat(String str) {
if (str.isEmpty()) {
return this;
}
return StringConcatHelper.simpleConcat(this, str);
}
从这段代码中可以看到,如果传入的字符串为空字符串,concat()方法将直接返回当前字符串对象本身;
否则,它会创建一个新的字符串对象。
处理空字符串的情况
如果你试图向concat()方法传递一个null值,将会导致NullPointerException:
public class Codekru {
public static void main(String[] args) {
String s1 = "hello";
s1 = s1.concat(null);
}
}
输出结果为:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "str" is null
同样地,如果你试图在一个null的字符串上调用concat()方法,也会导致NullPointerException:
public class Codekru {
public static void main(String[] args) {
String str = null;
str = str.concat("");
}
}
输出结果为:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.concat(String)" because "str" is null
通过上述内容,我们可以了解到Java中String类的concat()方法的工作原理及其使用时的一些注意事项。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。










