Strings Deep Dive — Immutability, StringBuilder, Text Blocks

String-এর গভীর বিশ্লেষণ — immutability, StringBuilder, text block

Read: ~30 min Intermediate 5 practice problems Live code runner

1. Strings Are Immutable — and Why It Matters

In Java, every String is immutable. Once created, its characters cannot change. When you write s = s + "!", you are not changing s — you are creating a new String and pointing s at it. Immutability is not a quirk; it is a deliberate design choice that makes Strings safe to share across threads, safe as HashMap keys, and cacheable inside the JVM.

Java-তে প্রতিটি String immutable — তৈরি হলে আর পাল্টানো যায় না। s = s + "!" লিখলে s পাল্টায় না — একটি নতুন String তৈরি হয়ে s তাকে point করে। এটি সুরক্ষা দেয় — thread-safe share, HashMap key হিসেবে নিরাপদ, এবং JVM ক্যাশ করতে পারে।
Consequence: concatenating a String in a loop with += is O(n²) because every iteration allocates a new String. For anything more than a few appends, use StringBuilder — it mutates in place, giving O(n).

2. The String Pool and Interning

Every String literal you write — "hello" — is placed in a special JVM-managed table called the String pool. Two different places in your code that write "hello" literally share the same object. That is why "hi" == "hi" returns true in Java, while new String("hi") == "hi" returns false — the new keyword forces a separate object.

প্রতিটি String literal ("hello") JVM-এর String pool-এ থাকে। একাধিক জায়গায় একই literal থাকলে তারা একই object share করে — তাই "hi" == "hi" true। কিন্তু new String("hi") জোর করে আলাদা object বানায় — তাই == false হয়। সমতা পরীক্ষা করতে সবসময় .equals() ব্যবহার করুন।
String pool — literals share one object String pool "hello" "world" a = "hello" b = "hello" new String("hello") separate object Figure 35.1 — একই literal একই object। new String(...) আলাদা object।

3. StringBuilder — The Concatenation Machine

StringBuilder is a mutable buffer of characters that grows as you append. For building strings in loops or from many pieces, it is vastly faster than +. When you are done, call toString() to get an immutable String.

StringBuilder একটি mutable character buffer — append করলে বড় হয়। loop-এ বা বহু অংশ থেকে string বানাতে +-এর চেয়ে বহু গুণ দ্রুত। শেষে toString() দিয়ে immutable String পাবেন।
Main.java
class Main {
    public static void main(String[] args) {
        // SLOW way — creates 1000 throw-away Strings
        long t0 = System.nanoTime();
        String s = "";
        for (int i = 0; i < 1000; i++) s += "x";
        long t1 = System.nanoTime();

        // FAST way — one buffer, grown in place
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 1000; i++) sb.append("x");
        String result = sb.toString();
        long t2 = System.nanoTime();

        System.out.println("String +=       : " + (t1 - t0) + " ns");
        System.out.println("StringBuilder   : " + (t2 - t1) + " ns");
        System.out.println("result length   : " + result.length());
    }
}
Note: a single concatenation like a + b + c is fine — the compiler actually turns it into a StringBuilder under the hood. The problem is loops.

4. Text Blocks — Multi-Line Strings Done Right (Java 15+)

Before text blocks, any multi-line SQL or JSON inside Java code was a hideous pile of "\n" and backslashes. Java 15 introduced text blocks with triple quotes """, which preserve line breaks and auto-trim leading whitespace to match the closing """.

আগে multi-line SQL বা JSON Java-তে লিখতে হলে "\n" আর backslash-এর জঙ্গল হতো। Java 15-এ text block এসেছে — triple quote """ দিয়ে। line break ঠিক থাকে এবং leading whitespace auto-trim হয়।
Main.java
class Main {
    public static void main(String[] args) {
        String sql = """
            SELECT id, name, email
            FROM   users
            WHERE  country = 'BD'
            ORDER BY name
            """;
        System.out.println(sql);

        String json = """
            {
              "name": "Raihan",
              "role": "admin"
            }
            """;
        System.out.println(json);
    }
}

5. String.format and formatted

For templated output, String.format uses the same format specifiers as C's printf: %s, %d, %.2f, %n (platform newline). Java 15 added an instance method .formatted(...) that pairs beautifully with text blocks.

template-এ output-এর জন্য String.format — specifier-গুলো C-র printf-এর মতোই (%s, %d, %.2f, %n)। Java 15-এ instance method .formatted(...) এসেছে — text block-এর সাথে সুন্দর যায়।
Main.java
class Main {
    public static void main(String[] args) {
        String line = String.format("%-10s %5d  %7.2f", "Rice", 3, 185.50);
        System.out.println(line);

        String tmpl = """
            User: %s
            Role: %s
            Age : %d
            """;
        System.out.println(tmpl.formatted("Raihan", "admin", 24));
    }
}

6. The Methods You Will Actually Use

MethodReturnsবাংলায়
length()character countঅক্ষর সংখ্যা
charAt(i)char at index iনির্দিষ্ট index-এর অক্ষর
substring(a, b)slice [a, b)নির্দিষ্ট অংশ কেটে নেয়
indexOf(s)first position or -1substring-এর প্রথম position
contains(s)booleanআছে কিনা
startsWith / endsWithbooleanশুরু/শেষ মিলছে কিনা
toLowerCase / toUpperCasenew stringcase পরিবর্তন
trim() / strip()new stringসামনে-পিছনের whitespace মুছে দেয়
replace(a, b)new stringএকটি অক্ষর/substring বদল
split(regex)String[]ভাগ করে array দেয়
isBlank() (Java 11+)booleanempty বা শুধু whitespace কিনা
repeat(n) (Java 11+)new stringn বার পুনরাবৃত্তি
Main.java
class Main {
    public static void main(String[] args) {
        String s = "  Hello, ABCL TECH!  ";
        System.out.println("length = " + s.length());
        System.out.println("strip  = [" + s.strip() + "]");
        System.out.println("upper  = " + s.strip().toUpperCase());
        System.out.println("contains TECH = " + s.contains("TECH"));
        System.out.println("replace = " + s.strip().replace("ABCL", "★"));
        System.out.println("repeat = " + "-".repeat(20));
    }
}

7. Vocabulary

TermMeaningবাংলায়
ImmutableCannot be modified after creation.তৈরির পর পরিবর্তন করা যায় না।
String poolJVM-managed cache of string literals.JVM-এর literal cache।
InterningDeduplicating equal strings into one pool entry.একই string এক object-এ যুক্ত করা।
StringBuilderMutable character buffer — fast concatenation.mutable buffer — দ্রুত concatenation।
Text blockMulti-line string literal with """.triple-quote multi-line literal।
Format specifierPlaceholder like %d, %s in format strings.format string-এর placeholder।

8. Practice Problems

  1. Use StringBuilder to reverse a string and print it.
    StringBuilder দিয়ে একটি string উল্টে print করুন।
    Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            String s = "Bangladesh";
            String r = new StringBuilder(s).reverse().toString();
            System.out.println(r);
        }
    }
  2. Explain in 3 sentences why s = s + "!" in a 100000-iteration loop is a performance disaster.
    তিন বাক্যে বলুন — ১ লক্ষ বার loop-এ s = s + "!" কেন performance disaster।
    Show Answer (উত্তর দেখুন)

    Answer: Each iteration allocates a brand-new String object and copies every character of the previous one into it, because Strings are immutable. The total work is 1 + 2 + 3 + ... + n copies, which is O(n²). With 100000 iterations that is 5 billion character copies — seconds of CPU for what should be milliseconds. StringBuilder mutates one growing buffer in O(n).

    প্রতিটি iteration-এ নতুন String object তৈরি হয়ে আগের সব character কপি হয় (immutable বলে)। মোট কাজ 1+2+3+...+n = O(n²)। ১ লক্ষ iteration মানে ৫ বিলিয়ন character copy — মিলিসেকেন্ডের কাজ সেকেন্ডে পরিণত হয়। StringBuilder একটি buffer mutate করে — O(n)।

  3. Given a CSV row "Raihan,24,Dhaka", split it and print each field on a separate line.
    "Raihan,24,Dhaka" CSV row-কে split করে প্রতিটি field আলাদা লাইনে print করুন।
    Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            String row = "Raihan,24,Dhaka";
            for (String part : row.split(",")) {
                System.out.println(part);
            }
        }
    }
  4. Use a text block to print a small HTML snippet.
    text block দিয়ে একটি ছোট HTML snippet print করুন।
    Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            String html = """
                <div class="card">
                  <h1>ABCL TECH</h1>
                  <p>Free Bangla Java Course</p>
                </div>
                """;
            System.out.println(html);
        }
    }
  5. Format a number as "Price: 1,200.50 BDT" using String.format.
    String.format দিয়ে "Price: 1,200.50 BDT" আকারে number format করুন।
    Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            double price = 1200.5;
            System.out.println(String.format("Price: %,.2f BDT", price));
        }
    }

Summary — Module 35

Strings in Java are immutable — a design that makes them safe but forces a mental shift: every modification produces a new object. For loops and heavy concatenation, reach for StringBuilder. Multi-line literals belong in text blocks ("""). Format strings with String.format or .formatted. Always compare with .equals(), never ==.

Java-তে String immutable — নিরাপদ, কিন্তু প্রতিটি পরিবর্তনে নতুন object। loop-এ StringBuilder। multi-line-এ text block (""")। format-এ String.format বা .formatted। সমতা পরীক্ষায় সবসময় .equals(), কখনো == নয়।

Next Module → Midterm Project — একটি বাস্তব CLI টুল বানান।