Java 中 concat() 方法用于在现有字符串末尾追加另一个字符串,创建新的字符串。具体用法包括:拼接多个字符串。向现有字符串中添加固定文本。在串联中使用。

Java 中 concat() 的用法
concat() 方法是 Java 中 String 类的一个内置方法,用于在现有字符串的末尾追加另一个字符串。
语法:
public String concat(String str)
参数:
立即学习“Java免费学习笔记(深入)”;
-
str- 要附加到现有字符串的字符串。
返回值:
- 一个新的字符串,它是现有字符串与附加字符串的连接。
用法:
concat() 方法可以在以下场景中使用:
-
拼接多个字符串:
String str1 = "Hello"; String str2 = "World"; String result = str1.concat(str2); //结果为 "HelloWorld"
-
向现有字符串中添加固定文本:
String str = "This is "; String addition = "a test"; String result = str.concat(addition); //结果为 "This is a test"
-
在串联中使用:
String str1 = "John"; String str2 = "Doe"; String result = "Name: ".concat(str1).concat(" ").concat(str2); //结果为 "Name: John Doe"
注意:
-
concat()方法会创建一个新字符串。它不会修改现有字符串。 - 如果
str为null,则concat()会生成一个"null"字符串。 -
concat()对不可变字符串执行高效的字符串连接。











