// 方法1: 使用 + 操作符
public class StringConcatExample1 {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "World";
        String result = str1 + " " + str2;
        System.out.println(result); // 输出: Hello World
    }
}
// 方法2: 使用 StringBuilder
public class StringConcatExample2 {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Hello").append(" ").append("World");
        String result = sb.toString();
        System.out.println(result); // 输出: Hello World
    }
}
// 方法3: 使用 StringBuffer(线程安全)
public class StringConcatExample3 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        sb.append("Hello").append(" ").append("World");
        String result = sb.toString();
        System.out.println(result); // 输出: Hello World
    }
}
// 方法4: 使用 String.join() 方法
public class StringConcatExample4 {
    public static void main(String[] args) {
        String result = String.join(" ", "Hello", "World");
        System.out.println(result); // 输出: Hello World
    }
}StringBuilder 是非线程安全的,但性能较高,适合在单线程环境中大量拼接字符串。StringBuffer 是线程安全的,但性能略低于 StringBuilder,适合在多线程环境中使用。String.join() 方法可以方便地将多个字符串通过指定的分隔符连接在一起,代码简洁易读。上一篇:java判断list是否为空
下一篇:deque java
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站