Code Logo

Build String with StringBuilder

Published at25 Jul 2026
Java OOP Easy 0 views
Like0

Write a Java function that takes three strings and returns a single concatenated string using StringBuilder. StringBuilder is Java's mutable sequence of characters, designed for efficient string building without the overhead of creating multiple intermediate String objects.

StringBuilder is a fundamental Java class for string manipulation. Unlike String concatenation with + which creates new String objects for each operation (causing O(n^2) memory usage), StringBuilder maintains an internal buffer and appends characters in O(1) amortized time per append. The toString() method converts the built content to an immutable String.

StringBuilder is not thread-safe (unlike StringBuffer which is synchronized). For single-threaded usage, StringBuilder is preferred for performance. Common methods include append() for adding strings, insert() for inserting at positions, delete() for removing ranges, and reverse() for reversing content.

Time complexity is O(n) where n is the total length of all input strings. Space complexity is O(n) for the internal buffer. StringBuilder grows dynamically, doubling capacity when full, similar to ArrayList.

Edge cases include empty strings (appended as empty), null strings (append("null") or NullPointerException depending on the overload used), and very large strings (buffer grows automatically).

Example Input & Output

Example 1
Input
"a","b","c"
Output
abc
Explanation

Simple concatenation

Example 2
Input
"","",""
Output
Explanation

Empty strings

Example 3
Input
"x","y","z"
Output
xyz
Explanation

Three letters

Example 4
Input
"Java"," is"," fun"
Output
Java is fun
Explanation

Phrase building

Example 5
Input
"Hello,"," ","World!"
Output
Hello, World!
Explanation

Concatenate three parts

Algorithm Flow

Recommendation Algorithm Flow for Build String with StringBuilder
Recommendation Algorithm Flow for Build String with StringBuilder

Solution Approach

class Solution {
    public String solution(String a, String b, String c) {
        StringBuilder sb = new StringBuilder();
        sb.append(a); sb.append(b); sb.append(c);
        return sb.toString();
    }
}

Best Answers

java - Approach 1
class Solution {
    public String solution(String a, String b, String c) {
        StringBuilder sb = new StringBuilder();
        sb.append(a); sb.append(b); sb.append(c);
        return sb.toString();
    }
}