A String is a reference type in java.lang. It represents an immutable sequence of UTF-16 code units (historically; since Java 9 the JVM may store Latin-1 compactly). It is not a primitive. The literal "Hi" is still an object.
Mental model: a String variable holds a reference to an object whose character data cannot change. Reassignment (s = s + "x") points the variable at a new object. The old object is unchanged and may later be collected.
Definition (immutability): after construction, a String’s length and contents cannot be mutated through any public API. Methods that look like they “change” a string return a new String.
StringBuilder), secrets you need to wipe from memory (char arrays / specialized APIs), or binary data (use byte[]).String a = "java";
String b = a.toUpperCase(); // a is still "java"; b is "JAVA"
a.concat("!"); // discarded unless assigned
Reference: String s = "Computer"; Indices are 0-based. Most instance methods throw NullPointerException if the receiver is null; many throw StringIndexOutOfBoundsException on a bad index.
| Method | Returns | Notes |
|---|---|---|
length() | int | UTF-16 code-unit count, not Unicode code-point count. "😊".length() is 2. |
isEmpty() | boolean | length() == 0. A string of spaces is not empty. |
isBlank() | boolean | Java 11. True if empty or only Unicode whitespace. |
charAt(i) | char | Code unit at index. Does not understand surrogate pairs. |
indexOf / lastIndexOf | int | -1 if not found. Overloads take char, String, and fromIndex. |
substring(b) / substring(b, e) | String | End exclusive. Since Java 7u6 this copies; it no longer shares the backing array. |
trim() | String | Strips code points ≤ U+0020 only. Prefer strip() (Java 11) for Unicode whitespace. |
strip / stripLeading / stripTrailing | String | Java 11. Unicode-aware whitespace. |
toLowerCase / toUpperCase | String | Locale-sensitive. Turkish I is a classic trap — pass Locale.ROOT for identifiers. |
equals / equalsIgnoreCase | boolean | Content. Never use == for user input. |
compareTo / compareToIgnoreCase | int | Lexicographic on UTF-16 units. Consistent with equals for the case-sensitive form. |
startsWith / endsWith / contains | boolean | Case-sensitive. contains takes a CharSequence. |
replace(old, new) | String | Char or CharSequence. Replaces all. Not a regex. |
replaceAll / replaceFirst | String | Regex. A literal dot is \\.. Easy production bug. |
split(regex) | String[] | Regex. Trailing empty strings are discarded unless you pass a negative limit. |
concat / + | String | + uses a builder in one expression; repeated + in a loop allocates many intermediates. |
String.valueOf(x) | String | Null-safe for objects: returns "null". Prefer over x.toString() when x may be null. |
String.join(delim, …) | String | Java 8. Null delimiter or elements throw NPE. |
repeat(n) | String | Java 11. n < 0 throws. |
formatted(args) | String | Java 15. Instance form of String.format. |
Integer.parseInt / valueOf | int / Integer | Parsing, not String methods. parseInt → primitive; valueOf → cached Integer where applicable. |
Text blocks (Java 15): """...""" for multiline literals. Incidental leading indentation is stripped. Use \s to keep a trailing space. Prefer them for SQL, JSON fixtures, and HTML snippets — not for secrets.
String sql = """
SELECT id, name
FROM users
WHERE active = true
""";
Immutability is why Strings are safe as HashMap keys and safe to share across threads without extra synchronization: once you publish a reference, nobody can change the characters underneath you.
new String("a") is a distinct object that copies the literal. Almost never write this.intern() returns the pooled instance. Do not intern arbitrary user input — you can pin memory for the life of the JVM.String a = "hi";
String b = "hi";
String c = new String("hi");
String d = "h" + "i"; // compile-time constant → pooled
String e = a.substring(0); // may be the same object (implementation)
System.out.println(a == b); // true (same interned instance)
System.out.println(a == c); // false
System.out.println(a.equals(c)); // true
System.out.println(a == d); // true
Professional rule: == on Strings is an intern/identity check. Production code compares content with equals. The only common == use is an intentional intern-table identity test, which you almost never need.
// Incorrect — NPE if name is null; also wrong if interned vs not
if (name == "admin") { ... }
// Incorrect — still NPE if name is null
if (name.equals("admin")) { ... }
// Correct — constant first, or Objects.equals
if ("admin".equals(name)) { ... }
if (java.util.Objects.equals(name, "admin")) { ... }
Mental model: String concatenation in a loop is typically O(n²) because each + copies the growing prefix. A StringBuilder is a mutable char buffer with amortized O(1) appends.
| Type | Mutable | Thread-safe | Use |
|---|---|---|---|
String | no | yes (immutable) | Values you share or store |
StringBuilder | yes | no | Default choice in one thread |
StringBuffer | yes | synchronized methods | Legacy. Prefer a local builder or a concurrent design. |
// Incorrect — quadratic + lots of garbage
String csv = "";
for (String cell : cells) {
csv += cell + ",";
}
// Correct
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cells.size(); i++) {
if (i > 0) sb.append(',');
sb.append(cells.get(i));
}
String csv = sb.toString();
// Also correct
String csv2 = String.join(",", cells);
a + b + c is compiled to one builder. That is fine.new StringBuilder(n)) when you know the length; growth copies the buffer.StringBuffer synchronization does not make compound operations atomic. Two threads doing append-then-read still race.StringBuilder across threads. Build locally, then publish the finished String.Complexity: charAt/length are O(1). indexOf and contains are O(n·m) naive search. substring is O(k) to copy k chars. Regex replaceAll/split can be much worse on crafted input (catastrophic backtracking) — compile a Pattern once, or avoid regex for simple delimiters.
equals is content equality, case-sensitive, null-safe on the receiver only if you call it on a known non-null.hashCode is cached on the String after first computation. That is why Strings are cheap map keys.compareTo is not locale collation. "a".compareTo("B") is positive because 'a' > 'B' in UTF-16. For dictionary order use Collator.equalsIgnoreCase is not the same as lowercasing both sides in a default locale (Turkish i/İ)."ANGER".compareTo("ANGEL"); // 'R' - 'L' = 6
"devote".compareTo("DEVOTE"); // 'd' - 'D' = 32
Natural order of String is consistent with equals. That matters if you use both HashMap and TreeMap with the same keys.
Java char is a UTF-16 code unit. A Unicode code point outside the BMP needs two chars (a surrogate pair). length(), charAt, and substring operate on code units. Use codePointAt, codePoints(), or offsetByCodePoints when you mean characters users see.
new String(bytes, StandardCharsets.UTF_8) and s.getBytes(StandardCharsets.UTF_8).getBytes() / new String(bytes) use the platform default charset. That is a production defect on servers that are not UTF-8.String as a bag of secret bytes. Encoding can change length; wiping a String is impossible because of immutability and copies.byte[] raw = text.getBytes(java.nio.charset.StandardCharsets.UTF_8); String again = new String(raw, java.nio.charset.StandardCharsets.UTF_8);
"a.b".split(".") splits on every character. Use Pattern.quote or indexOf.Locale.ROOT.char[] and wipe, or a dedicated secret type.isBlank() for user-facing “did they type anything?”%s vs %n (platform newline). Wrong format specifiers throw IllegalFormatException at runtime.These are the classic index/compareTo questions. Work them from 0-based indices and UTF-16 char values, then check the professional explanation.
Q1. Output of "CONCENTRATION".indexOf('T')
Answer: (c) 6 C0 O1 N2 C3 E4 N5 T6. First T is 6. lastIndexOf('T') would be 9.
Q2. Which returns a String?
Answer: (c) replace() The others return int or char. replace always returns a new String (even if nothing changed, implementations may return this).
Q3. compareTo when two strings are equal
Answer: 0 Not true/false. compareTo is an int, like Comparator.
Q4. "Remarkable".substring(6)
Answer: able R0 e1 m2 a3 r4 k5 a6 … End-exclusive two-arg form: substring(6, 10) is also "able".
Q5. "ANGER".compareTo("ANGEL")
Answer: 6 Common prefix ANGE, then 'R' − 'L' = 6. Sign tells order; magnitude is not something to depend on beyond “nonzero”.
indexOf vs lastIndexOf
indexOf is the first match from the left; lastIndexOf is the last. Both return -1 if absent. Both have fromIndex overloads (search forward vs backward).
length vs length()
Arrays expose a length field. String exposes a length() method. Collection types use size(). Mixing them is a compile error, not a runtime surprise.
compareTo vs equals
equals is a boolean content check. compareTo is a signed ordering. Do not write if (a.compareTo(b)) — that does not compile. For equality tests, use equals.
trim vs strip
trim uses a 20-year-old definition of space (≤ U+0020). strip uses Unicode whitespace (Java 11). User input from the web can include NBSP (U+00A0); trim will not remove it.
replace vs replaceAll
replace is literal. replaceAll is regex. Naming is unfortunate and a frequent production bug.
equals / Objects.equals, never ==, unless you are discussing intern identity on purpose.StringBuilder or String.join, not +=.StandardCharsets.UTF_8.strip/isBlank for user text; Locale.ROOT for case-folding tokens.split/replaceAll as regex. Quote literals. Compile hot Patterns once.length() is code units. Emoji and non-BMP text need code points.~ Good luck with your revision! ~