Java StringJoiner vs StringBuilder


StringJoiner

StringJointer was added to Java 8 in java.util package and is mostly used to add a delimiter between a sequence of Strings/Characters to join them.

Example of StringJoiner

    package org.code2care.examples;
    
    import java.util.StringJoiner;
    
    public class StringJoinerExample1 {
    
        public static void main(String[] args) {
            StringJoiner stringJoiner = new StringJoiner(",");
            stringJoiner.add("1");
            stringJoiner.add("2");
            stringJoiner.add("3");
            stringJoiner.add("4");
            System.out.println(stringJoiner.toString());
        }
    }
    Output:

    1,2,3,4



StringBuilder

StringBuilder is a legacy class available in Java since version 5 which is used to useful for dynamically constructing strings by appending, inserting, or modifying characters.


Example of StringBuilder

    package org.code2care.examples;
    
    public class StringBuilderExample {
    
        public static void main(String[] args) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("1");
            stringBuilder.append(",");
            stringBuilder.append("2");
            stringBuilder.append(",");
            stringBuilder.append("3");
            stringBuilder.append(",");
            stringBuilder.append("4");
            String result = stringBuilder.toString();
            System.out.println(result);
        }
    }
    
    Output:

    1,2,3,4


StringJoiner vs StringBuilder

StringJoinerStringBuilder
Join strings with a specific delimiter.Build and manipulate strings efficiently.
Available since Java 8Available since Java 5
StringJoiner are not mutable StringBuilder are mutable.
Specified during initialization.Appended using append method.
Join elements from a collection.Dynamically build strings with append or insert operations.
Efficient for joining strings with a delimiter.Efficient for dynamic string manipulations.
StringJoiner are Tread-Safe StringBuilder are not Thread-Safe

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap