Introduction & Syntax
Strings and StringBuilder · Study material
Strings in Java are everywhere: names, emails, passwords, URLs, JSON, log lines, user input. java.lang.String is a class, its objects are immutable (they never change once created), and string literals are shared through the string pool. For building text step by step, Java offers the mutable StringBuilder. "Why is String immutable?", "== vs equals()", "String vs StringBuilder vs StringBuffer" and programs like palindrome, anagram, reversing words and counting characters are some of the most frequently asked questions in Java interviews and placement tests. This page explains how strings work, every commonly used method, text blocks and formatting, and StringBuilder, with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – all compiled and run on Java 21.
On this page
- String immutability and the string pool
- Comparing strings: ==, equals, equalsIgnoreCase, compareTo
- The most used String methods
- split, join and conversions between strings, numbers and char arrays
- StringBuilder vs StringBuffer, and why += in a loop is slow
- Text blocks, String.format and formatted()
Strings are immutable objects
No String method changes the String it is called on: toUpperCase(), replace(), trim() and the rest return new Strings. That is why s.toUpperCase(); on its own does nothing useful. Immutability makes strings safe to share between threads, safe as HashMap keys (their hash code never changes) and safe for security-sensitive values such as file paths and class names.
String literals are stored in the string pool: the same literal anywhere in the program refers to the same object. new String("…") always creates a separate object, and intern() returns the pooled copy.
public class Main {
public static void main(String[] args) {
String s = "java";
s.toUpperCase(); // returns a NEW String – the result is thrown away
System.out.println(s);
s = s.toUpperCase(); // keep the result by reassigning
System.out.println(s);
String a = "LearnFrenzy"; // literals live in the string pool and are shared
String b = "LearnFrenzy";
String c = new String("LearnFrenzy");
System.out.println((a == b) + " " + (a == c) + " " + a.equals(c) + " " + (a == c.intern()));
}
}
java JAVA true false true true
Comparing strings
| Expression | Compares |
|---|---|
a == b | whether a and b are the same object (almost never what you want) |
a.equals(b) | the characters, case-sensitive |
a.equalsIgnoreCase(b) | the characters, ignoring case |
a.compareTo(b) | dictionary order: negative, 0 or positive |
Objects.equals(a, b) | like equals, but safe when either is null |
The most used String methods
public class Main {
public static void main(String[] args) {
String s = "Learn Java at LearnFrenzy";
System.out.println(s.length() + " " + s.charAt(6) + " " + s.indexOf("Learn") + " " + s.lastIndexOf("Learn") + " " + s.indexOf('z'));
System.out.println(s.substring(6, 10) + "|" + s.substring(14) + "|" + s.contains("Java") + " " + s.startsWith("Learn") + " " + s.endsWith("zy"));
System.out.println(s.toUpperCase() + " | " + s.toLowerCase());
System.out.println(s.replace("Learn", "Teach") + " | " + s.replace('a', '@'));
System.out.println("[" + " padded ".trim() + "] [" + " padded ".strip() + "] " + " ".isBlank() + " " + "".isEmpty());
System.out.println("ab".repeat(3) + " " + "Java".compareTo("Javascript") + " " + "apple".compareTo("banana") + " " + "Java".equalsIgnoreCase("JAVA"));
}
}
25 J 0 14 23 Java|LearnFrenzy|true true true LEARN JAVA AT LEARNFRENZY | learn java at learnfrenzy Teach Java at TeachFrenzy | Le@rn J@v@ @t Le@rnFrenzy [padded] [padded] true true ababab -6 -1 true
| Method | Returns |
|---|---|
length(), charAt(i), isEmpty(), isBlank() | size, character at index, empty / only whitespace |
substring(begin), substring(begin, end) | part of the string (end exclusive) |
indexOf(x), lastIndexOf(x), contains(x) | position (-1 if absent), presence |
startsWith, endsWith | prefix / suffix checks |
toUpperCase, toLowerCase | case conversion |
trim(), strip(), stripLeading() | remove surrounding whitespace (strip is Unicode-aware) |
replace(a, b), replaceAll(regex, b) | replace characters/text or regex matches |
split(regex), String.join(sep, parts) | break apart / glue together |
repeat(n), chars(), lines() | repeat, stream of chars, stream of lines |
compareTo, equalsIgnoreCase | ordering and comparison |
split, join and conversions
split takes a regular expression (so split on a dot needs "\\.") and drops trailing empty strings unless you pass a negative limit. Convert text to numbers with Integer.parseInt/Double.parseDouble (which throw NumberFormatException on bad input) and back with String.valueOf.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String csv = "Asha,21,Pune,,";
String[] parts = csv.split(","); // trailing empty strings are removed
String[] all = csv.split(",", -1); // limit -1 keeps them
System.out.println(parts.length + " " + all.length + " " + Arrays.toString(parts));
String words = " Java is fun ";
String[] w = words.trim().split("\\s+"); // regex: one or more spaces
System.out.println(Arrays.toString(w) + " " + String.join("-", w));
int age = Integer.parseInt("21");
double price = Double.parseDouble("99.50");
String back = String.valueOf(age) + "|" + price + "|" + Integer.toString(255, 16);
char[] chars = "hello".toCharArray();
Arrays.sort(chars);
System.out.println(back + " " + new String(chars) + " " + String.valueOf(chars, 0, 2));
}
}
3 5 [Asha, 21, Pune] [Java, is, fun] Java-is-fun 21|99.5|ff ehllo eh
StringBuilder and StringBuffer
StringBuilder is a mutable sequence of characters: append, insert, replace, delete, reverse and setCharAt change the same object and return it, so calls can be chained. StringBuffer has the same methods but is synchronised (thread-safe and slower); use StringBuilder unless several threads share one buffer.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java"); // mutable: methods change THIS object
sb.append(" 21").append('!').append(2026);
System.out.println(sb + " " + sb.length());
sb.insert(0, ">> ");
sb.replace(3, 7, "JAVA");
sb.deleteCharAt(sb.length() - 1);
sb.setCharAt(sb.length() - 1, '5');
System.out.println(sb);
sb.delete(0, 3).reverse();
System.out.println(sb + " " + sb.indexOf("AVAJ"));
String result = sb.toString(); // back to an immutable String
System.out.println(result.length());
}
}
Java 21!2026 12 >> JAVA 21!205 502!12 AVAJ 7 11
Why += in a loop is slow
Because Strings are immutable, s += x copies all existing characters into a new String each time – O(n²) work for n appends. A StringBuilder appends into one growing buffer. (A single expression like a + b + c is fine – the compiler optimises it.)
public class Main {
public static void main(String[] args) {
int n = 20_000;
long t1 = System.nanoTime();
String s = "";
for (int i = 0; i < n; i++) s += i % 10; // creates a new String every time: O(n²) copying
long slow = System.nanoTime() - t1;
long t2 = System.nanoTime();
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i++) sb.append(i % 10); // appends into one growing buffer: O(n)
String fast = sb.toString();
long quick = System.nanoTime() - t2;
System.out.println(s.length() + " " + fast.length() + " " + s.equals(fast));
System.out.println("StringBuilder faster: " + (quick < slow));
}
}
20000 20000 true StringBuilder faster: true
Text blocks and formatting
Text blocks (""", Java 15) write multi-line strings – JSON, SQL, HTML – without \n or escaped quotes; common indentation is removed automatically. String.format and the instance method formatted() fill in placeholders like %s, %d and %.2f.
public class Main {
public static void main(String[] args) {
String name = "Asha";
int marks = 91;
// Text block (Java 15): multi-line strings without \n and escaped quotes
String json = """
{
"name": "%s",
"marks": %d
}""".formatted(name, marks);
System.out.println(json);
String report = String.format("%-6s|%4d|%6.1f%%", name, marks, marks / 1.2);
System.out.println(report);
System.out.println("Hello".chars().filter(c -> c == 'l').count() + " " + "a-b-c".lines().count());
}
}
{
"name": "Asha",
"marks": 91
}
Asha | 91| 75.8%
2 1String vs StringBuilder vs StringBuffer
| String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Mutable | no | yes | yes |
| Thread-safe | yes (immutable) | no | yes (synchronised) |
| Speed for many changes | slow | fastest | slower than StringBuilder |
| equals compares content | yes | no (reference) | no (reference) |
| Use for | fixed text, keys, constants | building text in one thread | legacy code, shared buffers |
Common mistakes
- Comparing with == – use equals.
- Ignoring the result of toUpperCase, replace, trim … – Strings never change in place.
- split(".") or
split("|")– these are regex metacharacters; escape them. - substring(begin, end) – end is exclusive and must not exceed length().
- Calling methods on a null String – NullPointerException; put literals first in comparisons.
- += in loops – use StringBuilder.
- sb1.equals(sb2) on StringBuilders – compares references; compare toString() or use compareTo.
Key points to remember
- String is an immutable final class; methods return new Strings.
- Literals are pooled; new String creates a separate object.
- Compare contents with equals / equalsIgnoreCase / compareTo.
- split takes a regex; join glues parts with a separator.
- StringBuilder is mutable and fast; StringBuffer is its synchronised twin.
- Text blocks and formatted() make multi-line and formatted text easy.
Frequently asked questions
Why is String immutable in Java?
For safe sharing through the string pool, thread safety, stable hash codes for HashMap keys, and security (a validated file name or URL cannot be changed afterwards).
Where is the string pool?
On the heap (since Java 7); before that it was in the permanent generation.
How many objects does new String("a") create?
Up to two: the pooled literal "a" (if not already there) and the new String object on the heap.
Where can I learn more?
Read Java Strings and Java StringBuilder, then practise with the exercises below.