SoFunction
Updated on 2025-04-18

Java string processing full parsing (String, StringBuilder and StringBuffer)

Java string processing full parsing: String, StringBuilder and StringBuffer

1. String class basics

1. The nature of String

  • Immutable Objects: String objects in Java cannot be modified once they are created
  • Underlying implementation:based onprivate final char value[]Character array
  • String pool: A special storage area maintained by JVM, used to store string literals

2. Two ways to create String objects

// Method 1: Literal creation (storage directly into string pool)String s1 = "Hello";
// Method 2: Create new (create new object in heap memory)String s2 = new String("Hello");

3. String comparison

String a = "Java";
String b = "Java";
String c = new String("Java");
(a == b);      // true (points to the same object in the string pool)(a == c);      // false (different objects)((c)); // true(The content is the same)

4. Common methods

method illustrate Example
length() Get length "abc".length() → 3
charAt() Get the specified position character "abc".charAt(1) → ‘b’
substring() Intercept substrings "Hello".substring(1,3) → “el”
indexOf() Find character positions "Java".indexOf('a') → 1
toLowerCase() Turn lowercase "Java".toLowerCase() → “java”
toUpperCase() Convert capitalization "Java".toUpperCase() → “JAVA”
trim() Remove the beginning and end spaces " Java ".trim() → “Java”
split() Split string "a,b,c".split(",") → [“a”,“b”,“c”]
replace() Replace characters "Java".replace('a','o') → “Jovo”

2. StringBuilder and StringBuffer

1. Comparison of variable string classes

characteristic String StringBuilder StringBuffer
Variability Immutable variable variable
Thread safety yes no yes
performance Low high medium
Use scenarios A small number of operations Single threaded large number of operations Multi-threaded large number of operations

2. StringBuilder core method

StringBuilder sb = new StringBuilder();
// Chain call("Java").append(" is").append(" awesome!");
(sb); // "Java is awesome!"
(5, "really ");  // Insert(5, 12);        // delete(0, 4, "Kotlin"); // Replace();             // Reversal

3. StringBuffer thread safety example

class BufferThread extends Thread {
    private StringBuffer buffer;
    public BufferThread(StringBuffer buffer) {
         = buffer;
    }
    @Override
    public void run() {
        for(int i=0; i<100; i++){
            (i);
        }
    }
}
public class ThreadSafeDemo {
    public static void main(String[] args) throws InterruptedException {
        StringBuffer buffer = new StringBuffer();
        Thread t1 = new BufferThread(buffer);
        Thread t2 = new BufferThread(buffer);
        ();
        ();
        ();
        ();
        ("Final length: " + ()); // Correct output of 200    }
}

3. Performance comparison experiment

1. String stitching test

public class PerformanceTest {
    static final int LOOP_COUNT = 100000;
    public static void stringTest() {
        long start = ();
        String s = "";
        for(int i=0; i<LOOP_COUNT; i++){
            s += "a";
        }
        ("String takes time: " + (()-start) + "ms");
    }
    public static void builderTest() {
        long start = ();
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<LOOP_COUNT; i++){
            ("a");
        }
        ("StringBuilder takes time: " + (()-start) + "ms");
    }
    public static void bufferTest() {
        long start = ();
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<LOOP_COUNT; i++){
            ("a");
        }
        ("StringBuffer takes time: " + (()-start) + "ms");
    }
    public static void main(String[] args) {
        stringTest();    // About 4500ms        builderTest();  // About 5ms        bufferTest();    // About 10ms    }
}

2. Memory usage analysis

// Use jvisualvm to observe memory changespublic class MemoryDemo {
    public static void main(String[] args) throws InterruptedException {
        ("Start the test...");
        (10000);  // Wait for connection to VisualVM        // String will produce a large number of intermediate objects        String s = "";
        for(int i=0; i<100000; i++){
            s += i;
        }
        // StringBuilder creates only one object        StringBuilder sb = new StringBuilder();
        for(int i=0; i<100000; i++){
            (i);
        }
        (10000);  // Observe memory changes    }
}

4. String best practices

1. Select a policy

  • String: a small number of operations, string constants, as method parameters
  • StringBuilder: A large number of string operations in a single threaded environment
  • StringBuffer: A large number of string operations in multi-threaded environment

2. Optimization skills

// Bad writingString result = "";
for(String str : stringList) {
    result += str;  // Create a new String object every time the loop}
// Good writingStringBuilder builder = new StringBuilder();
for(String str : stringList) {
    (str);
}
String result = ();

3. String constant pool optimization

// Recommended writing method (using string pool)String s1 = "Hello";  
String s2 = "Hello";  // Multiplex s1 object// Writing method is not recommended (create redundant objects)String s3 = new String("Hello");  // Force creation of a new object

5. Expand knowledge

1. String compression (Java 9+)

Java 9, String is replaced by the underlying layerbyte[]Stored and added encoded flag fields:

// Check the string encoding methodString str = "Hello Java";
Field field = ("coder");
(true);
byte coder = (byte) (str);
(coder);  // 0expressLatin-1,1expressUTF-16

2. Underlying optimization of string stitching

// The Java compiler will automatically optimize to StringBuilderString s = "a" + "b" + "c";
// After compilation, it is equivalent to:String s = new StringBuilder().append("a").append("b").append("c").toString();

3. Regular expression application

// Verify the mailbox formatString email = "test@";
String regex = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
boolean isValid = (regex);
// Extract numbersString text = "Order 123 Amount 456";
Pattern pattern = ("\\d+");
Matcher matcher = (text);
while(()) {
    ("Find the number: " + ());
}

4. String formatting

// Traditional wayString info1 = ("Name: %s, Age: %d", "Zhang San", 25);
// Java 15+ text blocksString json = """
    {
        "name": "%s",
        "age": %d
    }
    """.formatted("Li Si", 30);

6. Advanced application cases

1. Implement a simple template engine

public class TemplateEngine {
    private final String template;
    public TemplateEngine(String template) {
         = template;
    }
    public String render(Map<String, Object> params) {
        StringBuilder result = new StringBuilder(template);
        for(<String, Object> entry : ()) {
            String key = "${" + () + "}";
            String value = ().toString();
            int index;
            while((index = (key)) != -1) {
                (index, index + (), value);
            }
        }
        return ();
    }
    public static void main(String[] args) {
        String template = "Welcome,${user}!Today is${day}。";
        Map<String, Object> params = new HashMap<>();
        ("user", "Wang Wu");
        ("day", "2023-05-20");
        TemplateEngine engine = new TemplateEngine(template);
        ((params));
    }
}

2. Comparison of string similarity

public class StringSimilarity {
    // Calculate the Levenshtein distance    public static int levenshteinDistance(String a, String b) {
        int[][] dp = new int[()+1][()+1];
        for(int i=0; i<=(); i++) dp[i][0] = i;
        for(int j=0; j<=(); j++) dp[0][j] = j;
        for(int i=1; i<=(); i++) {
            for(int j=1; j<=(); j++) {
                int cost = ((i-1) == (j-1)) ? 0 : 1;
                dp[i][j] = (
                    (dp[i-1][j]+1, dp[i][j-1]+1),
                    dp[i-1][j-1]+cost
                );
            }
        }
        return dp[()][()];
    }
    // Calculate the similarity percentage    public static double similarity(String a, String b) {
        int maxLen = ((), ());
        if(maxLen == 0) return 1.0;
        return (1 - (double)levenshteinDistance(a,b)/maxLen) * 100;
    }
    public static void main(String[] args) {
        String s1 = "kitten";
        String s2 = "sitting";
        ("Similarity: %.2f%%", similarity(s1, s2));
    }
}

7. Analysis of common interview questions

1. Why is String designed to be immutable?

  • Security: It will not be modified unexpectedly when passed as a parameter
  • Thread safety: No synchronization required to be used in multi-threaded
  • Cache hash: String is often used as the key of HashMap, hashCode can be cached
  • String pool: The basics of implementing string constant pools

2. String s = new String("xyz") creates several objects?

  • If "xyz" is not in the string pool: 2 (1 in the string pool, 1 in the heap)
  • If "xyz" is already in the string pool: 1 (new objects are created only in the heap)

3. How to efficiently splice string arrays?

// Use StringJoiner (Java 8+)StringJoiner sj = new StringJoiner(", ", "[", "]");
for(String str : array) {
    (str);
}
String result = ();
// Or use ()String result = (", ", array);

4. How to implement string inversion?

// Method 1: Use StringBuildernew StringBuilder(str).reverse().toString();
// Method 2: Character array swapchar[] chars = ();
for(int i=0, j=-1; i<j; i++,j--) {
    char temp = chars[i];
    chars[i] = chars[j];
    chars[j] = temp;
}
new String(chars);

8. Summary and best practices

1. Review of key points

  • String is an immutable object that is suitable for a small number of operations and as a constant
  • StringBuilder is a mutable, non-thread-safe string operation class
  • StringBuffer is a thread-safe version of StringBuilder
  • Avoid using String directly when operating a large number of strings

2. Performance optimization suggestions

  • Pre-allocated StringBuilder capacity:new StringBuilder(initialCapacity)
  • Avoid using it in a loop+Stitching strings
  • use()Alternative manual splicing and separating strings
  • Consider usingCharSequenceInterface as method parameter type

By deeply understanding the Java string processing mechanism, developers can write more efficient and robust string processing code, which is crucial for scenarios such as text processing, data formatting and inter-system communication in daily development.

This is all about this article about Java string processing. For more related Java string processing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!