Java字符串拼接的方法有以下几种:
- 使用"+“运算符:可以使用”+"运算符将两个字符串拼接在一起。
String str1 = "Hello"; String str2 = "World"; String result = str1 + str2; // "HelloWorld"
- 使用concat()方法:可以使用String类的concat()方法将两个字符串拼接在一起。
String str1 = "Hello"; String str2 = "World"; String result = str1.concat(str2); // "HelloWorld"
- 使用StringBuilder或StringBuffer类:StringBuilder和StringBuffer类是可变字符串类,提供了append()方法来拼接字符串。
StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append("World"); String result = sb.toString(); // "HelloWorld" // 或者使用链式调用 String result = new StringBuilder().append("Hello").append("World").toString(); // "HelloWorld"
需要注意的是,StringBuilder类是非线程安全的,而StringBuffer类是线程安全的,所以在单线程环境下,推荐使用StringBuilder类。