在 Java 中连接字符串
-
+运算符可以连接多种类型的值,而concat()只能连接字符串值 -
+如果值是空的,会生成一个新的String,而concat()则返回相同的值 -
+将连接null而concat()将抛出一个异常 -
+可以连接多个值,而concat()只能取一个值
今天,我们要看的是 concat() 和+ 操作符之间的区别。它们都是用来连接字符串的,但我们在这里要找出它们之间的不同之处。
+ 运算符可以连接多种类型的值,而 concat() 只能连接字符串值
+ 和 concat() 的第一个大区别是,我们可以用+ 操作符用 String 连接多种数据类型,但 concat() 方法被限制为只能取一个 String 类型的值。
如果我们看一下下面的情况,当我们使用+ 连接值时,任何数据类型的每个值都会使用 toString() 方法转换为 String。
下面的例子表明,我们可以将一个 int b 连接到一个 String a。但如果我们在 concat() 上尝试这样做,它将给出一个运行时错误,因为它不能接受一个 int 类型的值。
package com.company;
public class Main {
public static void main(String[] args) {
String a = "String A-";
int b = 5;
System.out.println(a + b);
}
}
输出:
String A-5
+ 如果值是空的,会生成一个新的 String,而 concat() 则返回相同的值
接下来要记下来的最大区别是,+ 每次得到一个值时,即使其长度为零,也会生成一个新的 String。但是 concat() 只有在遇到值的长度大于零时才会生成一个新的字符串。
如果我们要比较两个字符串,这可能会改变很多结果,就像我们下面所做的那样。第一个比较是在使用 concat() 对字符串进行连接时进行的,而第二个比较则显示了用+ 连接的两个字符串的比较结果。
package com.company;
public class Main {
public static void main(String[] args) {
String a = "String A";
String b = "";
String d = a.concat(b);
if (d == a) {
System.out.println("String d and a are equal using concat");
} else {
System.out.println("String d and a are NOT equal using concat");
}
String e = a + b;
if (e == a) {
System.out.println("String e and a are equal using plus operator");
} else {
System.out.println("String e and a are NOT equal plus operator");
}
}
}
输出:
String d and a are equal using concat
String e and a are NOT equal plus operator
+ 将连接 null 而 concat() 将抛出一个异常
在下面的例子中,我們可以看到,如果我們用 null 初始化變量 b,它仍然會正確地連接。這是因為 + 操作符將每個值轉換為 String,然後將它們連接起來。
package com.company;
public class Main {
public static void main(String[] args) {
String a = "String A-";
String b = null;
System.out.println(a + b);
}
}
输出:
String A-null
与+ 不同的是,当我们把 b 连接到 a 时,其中有 null,它会抛出一个 NullPointerException,一般来说,这是正确的输出。
package com.company;
public class Main {
public static void main(String[] args) {
String a = "String A-";
String b = null;
System.out.println(a.concat(b));
}
}
输出:
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.concat(String.java:1937)
at com.company.Main.main(Main.java:14)
+ 可以连接多个值,而 concat() 只能取一个值
+ 运算符可以像我们在下面的例子中那样连接多个值。不过,由于 concat() 函数只接受一个参数,它不能连接两个以上的值。
package com.company;
public class Main {
public static void main(String[] args) {
String a = "String A-";
String b = "String B-";
String c = "String C";
System.out.println(a + b + c);
System.out.println(a.concat(b));
}
}
输出:
String A-String B-String C
String A-String B-
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn