Thursday, February 13, 2020

Java Strings Part 2

String pieces (back) together
Use the + operator. The compiler implicitly constructs a StringBuilder for you and uses its append() methods
StringBuffer -> synchronized
StringBuilder -> not synchronized -> faster and preferable for single-threaded use. (not threadsafe)
AbstractStringBuilder -> parent of both

Example

public class StringBuilderExample {

    public static void main(String[] argv) {
        String s1 = "Hello" + ", " + "World";
        System.out.println(s1); //Hello, World
        
        StringBuilder sb2 = new StringBuilder();
        sb2.append("Hello");
        sb2.append(',');
        sb2.append(' ');
        sb2.append("World");
        String s2 = sb2.toString();
        System.out.println(s2); //Hello, World

        System.out.println(new StringBuilder().append("Hello").append(',').append(' ').append("World"));
        //Hello, World
    }
}


List of items into a comma-separated list

import java.util.StringTokenizer;

public class StringBuilderComma {
    public static final String SAMPLE_STRING = "HELLO WORLD OF JAVA";
    public static void main(String[] argv) {
        StringBuilder sb1 = new StringBuilder();
        for (String word : SAMPLE_STRING.split(" ")) {
            if (sb1.length() > 0) {
                sb1.append(", ");
            }
            sb1.append(word);
        }
        System.out.println(sb1); //HELLO, WORLD, OF, JAVA

        
        StringTokenizer st = new StringTokenizer(SAMPLE_STRING);
        StringBuilder sb2 = new StringBuilder();
        while (st.hasMoreElements()) {
            sb2.append(st.nextToken());
            if (st.hasMoreElements()) {
                sb2.append(", ");
            }
        }
        System.out.println(sb2); //HELLO, WORLD, OF, JAVA

    }
}
Java Strings Part 3

No comments:

Post a Comment