Strings Deep Dive — Immutability, StringBuilder, Text Blocks
String-এর গভীর বিশ্লেষণ — immutability, StringBuilder, text block
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.
String immutable — তৈরি হলে আর পাল্টানো যায় না। s = s + "!" লিখলে s পাল্টায় না — একটি নতুন String তৈরি হয়ে s তাকে point করে। এটি সুরক্ষা দেয় — thread-safe share, HashMap key হিসেবে নিরাপদ, এবং JVM ক্যাশ করতে পারে।
+= 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.
"hello") JVM-এর String pool-এ থাকে। একাধিক জায়গায় একই literal থাকলে তারা একই object share করে — তাই "hi" == "hi" true। কিন্তু new String("hi") জোর করে আলাদা object বানায় — তাই == false হয়। সমতা পরীক্ষা করতে সবসময় .equals() ব্যবহার করুন।
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 পাবেন।
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());
}
}
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 """.
"\n" আর backslash-এর জঙ্গল হতো। Java 15-এ text block এসেছে — triple quote """ দিয়ে। line break ঠিক থাকে এবং leading whitespace auto-trim হয়।
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.
String.format — specifier-গুলো C-র printf-এর মতোই (%s, %d, %.2f, %n)। Java 15-এ instance method .formatted(...) এসেছে — text block-এর সাথে সুন্দর যায়।
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
| Method | Returns | বাংলায় |
|---|---|---|
length() | character count | অক্ষর সংখ্যা |
charAt(i) | char at index i | নির্দিষ্ট index-এর অক্ষর |
substring(a, b) | slice [a, b) | নির্দিষ্ট অংশ কেটে নেয় |
indexOf(s) | first position or -1 | substring-এর প্রথম position |
contains(s) | boolean | আছে কিনা |
startsWith / endsWith | boolean | শুরু/শেষ মিলছে কিনা |
toLowerCase / toUpperCase | new string | case পরিবর্তন |
trim() / strip() | new string | সামনে-পিছনের whitespace মুছে দেয় |
replace(a, b) | new string | একটি অক্ষর/substring বদল |
split(regex) | String[] | ভাগ করে array দেয় |
isBlank() (Java 11+) | boolean | empty বা শুধু whitespace কিনা |
repeat(n) (Java 11+) | new string | n বার পুনরাবৃত্তি |
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
| Term | Meaning | বাংলায় |
|---|---|---|
| Immutable | Cannot be modified after creation. | তৈরির পর পরিবর্তন করা যায় না। |
| String pool | JVM-managed cache of string literals. | JVM-এর literal cache। |
| Interning | Deduplicating equal strings into one pool entry. | একই string এক object-এ যুক্ত করা। |
| StringBuilder | Mutable character buffer — fast concatenation. | mutable buffer — দ্রুত concatenation। |
| Text block | Multi-line string literal with """. | triple-quote multi-line literal। |
| Format specifier | Placeholder like %d, %s in format strings. | format string-এর placeholder। |
8. Practice Problems
-
Use
StringBuilderto reverse a string and print it.StringBuilderদিয়ে একটি string উল্টে print করুন।Show Answer (উত্তর দেখুন)
Main.javaclass Main { public static void main(String[] args) { String s = "Bangladesh"; String r = new StringBuilder(s).reverse().toString(); System.out.println(r); } } -
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
Stringobject 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.StringBuildermutates one growing buffer in O(n).প্রতিটি iteration-এ নতুন
Stringobject তৈরি হয়ে আগের সব character কপি হয় (immutable বলে)। মোট কাজ 1+2+3+...+n = O(n²)। ১ লক্ষ iteration মানে ৫ বিলিয়ন character copy — মিলিসেকেন্ডের কাজ সেকেন্ডে পরিণত হয়।StringBuilderএকটি buffer mutate করে — O(n)। -
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.javaclass Main { public static void main(String[] args) { String row = "Raihan,24,Dhaka"; for (String part : row.split(",")) { System.out.println(part); } } } -
Use a text block to print a small HTML snippet.text block দিয়ে একটি ছোট HTML snippet print করুন।
Show Answer (উত্তর দেখুন)
Main.javaclass 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); } } -
Format a number as
"Price: 1,200.50 BDT"usingString.format.String.formatদিয়ে"Price: 1,200.50 BDT"আকারে number format করুন।Show Answer (উত্তর দেখুন)
Main.javaclass 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 ==.
StringBuilder। multi-line-এ text block (""")। format-এ String.format বা .formatted। সমতা পরীক্ষায় সবসময় .equals(), কখনো == নয়।