concat()方法
该Java字符串concat()方法将一个字符串连接到另一个字符串的末尾。此方法返回一个字符串,并将传递给该方法的字符串的值附加到字符串的末尾。
例:
// Java program to demonstrate
// working of concat() method
class Gfg {
public static void main(String args[])
{
String s = "Gfg";
s = s.concat("! is the best.");
System.out.println(s);
}
}
|
输出:
Gfg! is the best.
+运算符
+运算符用于在两侧连接字符串。
例:
// Java program to demonstrate
// working of concat() method
class Gfg {
public static void main(String args[])
{
String s1 = "Gfg";
String s2 = "! is the best";
String s3 = s1 + s2;
System.out.println(s3);
}
}
|
输出:
Gfg! is the best.
尽管 concat()和+运算符都用于串联字符串,但是它们之间存在一些区别:
- concat()方法和+运算符的参数数量:
- CONCAT()方法仅接受一个参数字符串,并将其与其他字符串连接。
- +运算符接受任意数量的参数并连接所有字符串。
public class GFG {
public static void main(String[] args)
{
String s = "Geeks", t = "for", g = "geeks";
System.out.println(s + t + g);
System.out.println(s.concat(t));
}
}
|
输出:
Geeksforgeeks
Geeksfor
- 参数类型:
- strong-> concat()方法仅接受字符串参数,如果参数中指定了其他任何类型,则将引发错误。
- +运算符接受任何类型并转换为字符串类型,然后将字符串连接起来。
- concat()方法引发java.lang.NullPointer异常
- concat()方法当字符串与null连接时,抛出NullPointer异常
- +运算符字符串与null串联时未引发任何异常。
public class GFG {
public static void main(String[] args)
{
String s = "Geeks";
String r = null;
System.out.println(s + r);
// It raises an NullPointer Exception
System.out.println(s.concat(r));
}
}
|
输出:
Geeksnull
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.concat(String.java:2027)
at GFG.main(GFG.java:7)
- 创建一个新的String对象。
- concat()方法将两个字符串连接起来并仅返回字符串长度大于0的新字符串对象,否则返回相同的对象。
- +运算符每次都创建一个新的字符串对象,与字符串长度无关。
public class GFG {
public static void main(String[] args)
{
String s = "Geeks", g = "";
String f = s.concat(g);
if (f == s)
System.out.println("Both are same");
else
System.out.println("not same");
String e = s + g;
if (e == s)
System.out.println("Both are same");
else
System.out.println("not same");
}
}
|
输出:
Both are same
not same
- 性能:
concat()方法胜过+运算符,因为仅当字符串长度大于零(0)时,它才会创建一个新对象,但是+运算符始终会创建一个新字符串,而与字符串的长度无关。
差异表:
点 |
concat()方法 |
+运算符 |
定义 |
一种concat()方法是组合两个字符串的方法。 |
+运算符用于连接任意数量的字符串。 |
参数数量 |
在CONCAT()方法,仅接受字符串的一个参数,然后将其与另一个字符串连接。 |
在+运算符接受任意数量的参数并组合所有字符串。 |
参数类型 |
CONCAT()方法仅接受字符串类型的参数。 |
+运算符接受任何类型的参数并将其转换为字符串类型,然后将它们组合。 |
创建新的字符串 |
CONCAT()将两个字符串连接起来,并仅在字符串长度大于0的情况下返回新的字符串对象,否则返回相同的对象。 |
+运算符每次与字符串长度无关都创建一个新的字符串对象。 |
空指针异常 |
在CONCAT()当string与null串联时,此方法引发NullPointer Exception。 |
+运算符连接字符串,没有任何错误。 |
性能 |
concat()方法比+运算符更好,因为它仅在字符串长度大于零(0)时创建一个新对象,因此它使用较少的内存。 |
+运算符始终会创建一个新字符串,而与字符串长度无关,因此会占用更多内存。 |
|