字符串 concat()
方法的语法为:
string.concat(String str)
在这里, 字符串是String
类的对象。
concat()参数
concat()
方法采用单个参数。
- str-要连接的字符串
concat()返回值
- 返回一个字符串 ,该字符串是
string
和str
的串联(参数字符串)
示例:Java concat()
class Main {
public static void main(String[] args) {
String str1 = "Learn ";
String str2 = "Java";
// concatenate str1 and str2
System.out.println(str1.concat(str2)); // "Learn Java"
// concatenate str2 and str11
System.out.println(str2.concat(str1)); // "JavaLearn "
}
}
使用+运算符进行串联
在Java中,您还可以使用+
运算符来连接两个字符串。例如,
class Main {
public static void main(String[] args) {
String str1 = "Learn ";
String str2 = "Java";
// concatenate str1 and str2
System.out.println(str1 + str2); // "Learn Java"
// concatenate str2 and str11
System.out.println(str2 + str1); // "JavaLearn "
}
}
concat()与+运算符进行级联
concat() | the + Operator |
---|---|
Suppose, str1 is null and str2 is "Java" . Then, str1.concat(str2) throws NullPointerException. |
Suppose, str1 is null and str2 is "Java" . Then, str1 + str2 gives “nullJava”. |
You can only pass a String to the concat() method. |
If one of the operands is a string and another is a non-string value. The non-string value is internally converted to a string before concatenation. For example, "Java" + 5 gives "Java5" . |