Java Strings: Concatenation, Substrings, Immutability and Comparing with equals
The essentials of Java's String class: joining strings with + and String.join, repeat and split, indexes and substring, why strings are immutable and shared, why you must compare strings with equals instead of ==, compareTo, and empty vs null strings.
kvi5hnuCode Sprout team member12 min readOn this page
Text is everywhere in programs: names, messages, file contents, web requests. In Java, text is represented by the String class. Conceptually, a string is a sequence of Unicode characters. As the char/Unicode article showed, the exact encoding is complicated, but most of the time you don't need to care: you get strings from literals or methods, and you work with them through the methods of String.
A string literal such as "Hello, World!" is an object (an instance) of the String class. Strings look a bit like primitive values (they have literals and the + operator), but they are objects, and that difference explains several of the rules in this article.
Concatenation with +
The + operator joins (concatenates) two strings:
String first = "Ada";
String last = "Lovelace";
String full = first + " " + last; // "Ada Lovelace"
+ joins exactly what it's given, so you need to add spaces yourself: first + last is "AdaLovelace".
When you concatenate a string with a non-string value, the value is converted to a string first. This is how you build output messages:
public class Solution {
public static void main(String[] args) {
String first = "Ada";
String last = "Lovelace";
String full = first + " " + last;
System.out.println(full);
int age = 36;
System.out.println("Age: " + age);
System.out.println("Next year, you'll be " + age + 1);
System.out.println("Next year, you'll be " + (age + 1));
System.out.println(1 + 2 + " apples");
System.out.println("apples: " + 1 + 2);
String all = String.join(" / ", "S", "M", "L", "XL");
System.out.println(all);
System.out.println("Java".repeat(3));
System.out.println("-".repeat(20));
}
}
Ada Lovelace
Age: 36
Next year, you'll be 361
Next year, you'll be 37
3 apples
apples: 12
S / M / L / XL
JavaJavaJava
--------------------
String.join and repeat
String.join(delimiter, parts…)joins several strings with a separator between them (but not at the ends):String.join(" / ", "S", "M", "L", "XL")→"S / M / L / XL". It also accepts a list or array of strings.s.repeat(n)(Java 11+) returnssrepeatedntimes. It's handy for separator lines:"-".repeat(20).
Splitting Strings
The split method breaks a string into parts wherever a separator occurs, and returns them as an array of strings (arrays are covered in detail later in this part):
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
String[] words = "Hello, World!".split(" ");
System.out.println(words.length + " " + Arrays.toString(words));
System.out.println(Arrays.toString("red, green ,blue".split("\\s*,\\s*")));
System.out.println(Arrays.toString("one two\tthree".split("\\s+")));
System.out.println(Arrays.toString("www.example.com".split("\\.")));
System.out.println(Arrays.toString("a,b,,c,,".split(",")));
}
}
2 [Hello,, World!]
[red, green, blue]
[one, two, three]
[www, example, com]
[a, b, , c]
The argument of split is a regular expression (a small pattern language for describing text), not a plain string. That's why splitting on a period needs "\\.": in a regular expression, . means "any character". Useful patterns:
| Pattern (as a Java string) | Splits on |
|---|---|
"\\s+" | one or more whitespace characters (spaces, tabs, newlines) |
"\\s*,\\s*" | a comma with optional whitespace around it |
"\\." | a literal period |
"\\PL+" | any run of non-letters (leaves only words) |
"\\R" | any kind of line break (\n, \r\n, …) |
"\\b" | word boundaries |
"\\b{g}" | grapheme cluster boundaries: what users perceive as characters (Java 9+) |
Note the last line of the example: trailing empty strings are dropped ("a,b,,c,," gives four parts, not six), but empty strings in the middle are kept.
The grapheme pattern is the right tool when you really need "user-perceived characters". "Ciao 🇮🇹".split("\\b{g}") gives six parts, C, i, a, o, a space, and the complete flag, even though the flag is four chars.
Indexes, length and charAt
A string's characters (more precisely, its char code units) are numbered from 0, like arrays in C and C++:

| Method | Returns |
|---|---|
s.length() | the number of char values (13 for "Hello, World!") |
s.charAt(i) | the char at index i, for 0 ≤ i ≤ length() - 1 |
s.indexOf(sub) | the index where sub first occurs, or -1 if it doesn't |
s.indexOf(sub, from) | the first occurrence at or after index from |
s.lastIndexOf(sub) | the index of the last occurrence, or -1 |
Indexing outside the range (charAt(13) here, or charAt(-1)) throws a StringIndexOutOfBoundsException.
Substrings
substring extracts part of a string:
s.substring(begin, end)returns the characters from indexbeginup to but not including indexend.s.substring(begin)returns everything frombeginto the end.
public class Solution {
public static void main(String[] args) {
String greeting = "Hello, World!";
System.out.println(greeting.length());
System.out.println(greeting.charAt(0) + " " + greeting.charAt(greeting.length() - 1));
int comma = greeting.indexOf(",");
System.out.println(comma);
String hello = greeting.substring(0, comma);
String world = greeting.substring(comma + 2);
System.out.println(hello + " | " + world);
System.out.println(greeting.indexOf("o") + " " + greeting.lastIndexOf("o") + " " + greeting.indexOf("xyz"));
System.out.println(greeting.substring(7, 12).length());
}
}
13
H !
5
Hello | World!
4 8 -1
5
The "end is exclusive" convention has a nice property: s.substring(a, b) always has length b - a. substring(0, 5) has 5 characters, and substring(7, 12) has 5.
Strings Are Immutable
The String class has no methods that change a string. You can't swap the last letters of "Teacup" to make "Teapot". Instead, you build a new string and make the variable refer to it:
String drink = "Teacup";
int n = drink.indexOf("cup");
drink = drink.substring(0, n) + "pot"; // "Teapot"
Methods that seem to change a string, such as toUpperCase, replace, strip or substring, all return a new string and leave the original untouched:
public class Solution {
public static void main(String[] args) {
String drink = "Teacup";
String alias = drink; // both refer to the same string
int n = drink.indexOf("cup");
drink = drink.substring(0, n) + "pot";
System.out.println(drink); // the variable now refers to a new string
System.out.println(alias); // the original string is unchanged
String shout = alias.toUpperCase();
System.out.println(alias + " " + shout);
}
}
Teapot
Teacup
Teacup TEACUP

Objects whose state can't change after creation are called immutable. Just as the number 3 is always 3, the string "Teacup" always contains T, e, a, c, u, p. What can change is which string a variable refers to, just as an int variable can hold 3 now and 4 later.
Why make strings immutable?
Building a new string for every change sounds inefficient, and sometimes it is (see StringBuilder in the next article). But immutability brings big advantages:
- Sharing is safe. Many variables, objects and threads can refer to the same string without any risk of one of them changing it under the others. The compiler and JVM keep a string pool where identical string literals are stored only once.
- Security and reliability. A file name or URL checked by security code can't be modified afterwards by other code.
- Hashing. A string's hash code can be computed once and cached, which makes strings ideal keys in hash maps.
- Thread safety comes for free.
Most programs compare and pass strings around far more often than they modify them, so Java's designers decided that efficient sharing outweighs the cost of creating new strings.
Comparing Strings: equals, Not ==
To test whether two strings contain the same characters, use equals:
s.equals(t) // true if s and t contain the same characters
"Hello".equals(greeting) // literals work too
"Hello".equalsIgnoreCase("hello") // true: ignores upper/lowercase differences
Never use == to compare strings. For objects, == tests identity: whether two variables refer to the same object in memory. Two different string objects can contain identical text:
public class Solution {
public static void main(String[] args) {
String greeting = "Hello";
String computed = greeting.substring(0, 3) + "lo"; // built at runtime
System.out.println(computed);
System.out.println(greeting == "Hello"); // literals are shared
System.out.println(computed == greeting); // different objects!
System.out.println(computed.equals(greeting)); // same characters
System.out.println("hello".equalsIgnoreCase(greeting));
System.out.println(computed.intern() == greeting);
System.out.println("apple".compareTo("banana"));
System.out.println("banana".compareTo("apple"));
System.out.println("Apple".compareTo("apple"));
System.out.println("apple".compareTo("apple"));
System.out.println("Zebra".compareToIgnoreCase("apple") > 0);
}
}
Hello
true
false
true
true
true
-1
1
-32
0
true

Why does greeting == "Hello" give true? Identical string literals are shared from the string pool, so both refer to the same object. Strings computed at runtime (by substring, + with variables, reading input, and so on) are new objects. One more twist: constant expressions are evaluated by the compiler, so "Hel" + "lo" (or a final String constant plus a literal) becomes the pooled literal "Hello", and == returns true there too. Concatenating a non-final variable happens at run time and creates a new object. So == sometimes "works", which makes the bug worse: code that passes a quick test can fail with real input. Always use equals. (intern() returns the pooled copy of a string, which is why computed.intern() == greeting is true. You'll rarely need it.)
Ordering strings: compareTo
s.compareTo(t) compares strings in dictionary order (more precisely, by char values):
- a negative number if
scomes beforet, - zero if they're equal,
- a positive number if
scomes aftert.
Only the sign is meaningful. "Apple".compareTo("apple") is −32 because uppercase letters have smaller codes than lowercase ones ('A' is 65, 'a' is 97), so uppercase words sort first. compareToIgnoreCase ignores case. You could test equality with compareTo(...) == 0, but equals is clearer. For sorting text in a human language (where "é" should sort near "e"), use java.text.Collator.
Empty Strings and null
There are two different ways for a string variable to have "nothing":
Empty string "" | null | |
|---|---|---|
| What it is | A real String object with length 0 | No object at all |
s.length() | 0 | throws NullPointerException |
| How to test | s.isEmpty() (or s.length() == 0, or s.equals("")) | s == null |
isBlank() (Java 11+) is true for strings that are empty or contain only whitespace.
public class Solution {
public static void main(String[] args) {
String empty = "";
String blank = " ";
String missing = null;
System.out.println(empty.isEmpty() + " " + empty.length());
System.out.println(blank.isEmpty() + " " + blank.isBlank());
System.out.println(missing == null);
System.out.println(missing != null && !missing.isEmpty());
System.out.println("value: " + missing);
try {
System.out.println(missing.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}
System.out.println("Hello".equals(missing));
}
}
true 0
false true
true
false
value: null
NullPointerException
false
Points to remember:
- Calling any method on
nullthrows aNullPointerException. To check that a string is neither null nor empty, testnullfirst:s != null && !s.isEmpty(). The short-circuit&&makes this safe. - Concatenating
nullproduces the text"null". That's rarely what you want in output. - Writing the literal first,
"Hello".equals(input), never throws, even ifinputisnull. (Objects.equals(a, b)is another null-safe option.)
null is a general concept for all object variables and is discussed further in the objects and classes part.
Common questions
Why does "a,b,,c,,".split(",") return 4 parts?
split(regex) removes trailing empty strings. Empty strings in the middle are kept. To keep the trailing ones as well, pass a negative limit: "a,b,,c,,".split(",", -1) returns all 6 parts. A leading separator always produces an empty first element: ",a".split(",") is ["", "a"].
Should I call intern() so that I can compare strings with ==?
No. intern() returns the pooled copy, so == then works, but it is easy to forget on one path, and the pool has costs of its own. Use equals. It is fast, and it first checks whether the two references are the same object anyway.
Is "Hello".equals(s) better than s.equals("Hello")?
It is safer, because it can't throw when s is null. Some teams prefer Objects.equals(s, "Hello"). If s should never be null, s.equals("Hello") is fine, and a NullPointerException then points straight at the real bug.
How do I compare strings ignoring case?
Use a.equalsIgnoreCase(b) for equality and a.compareToIgnoreCase(b) or String.CASE_INSENSITIVE_ORDER for sorting. These compare char by char, which is fine for identifiers. For human-language text, use a java.text.Collator with the strength set to ignore case and accents.
Does substring copy characters or share them?
Since Java 7u6, substring copies the characters into a new string. That avoids a memory leak that the old sharing design could cause, where a tiny substring kept a huge original string alive. Taking substrings of large strings in a loop therefore costs memory and time proportional to their length.
Summary
- A
Stringis an immutable sequence ofcharvalues; literals like"Hi"areStringobjects. +concatenates and converts other values to strings. Mind left-to-right evaluation:"x" + 1 + 2is"x12".String.join(delim, …),repeat(n)andsplit(regex)combine and break apart strings.splittakes a regular expression and drops trailing empty strings.- Indexes run from 0 to
length() - 1.substring(a, b)coversatob - 1and has lengthb - a;indexOfreturns -1 when nothing is found. - Strings are immutable: methods return new strings. Remember to use the result.
- Compare contents with
equals/equalsIgnoreCase, order withcompareTo. Never use==for string contents. ""is an empty string;nullis no string at all. Checks != null && !s.isEmpty();isBlank()also treats whitespace-only strings as blank.
Practice Questions
What is printed by System.out.println("Sum: " + 3 + 4); and System.out.println(3 + 4 + " is the sum");?
Sum: 34 (left to right: the string absorbs 3, then 4) and 7 is the sum (3 + 4 is computed first, as both are numbers).
Given String s = "programming";, what are s.substring(3, 7), s.indexOf("g"), s.lastIndexOf("g") and s.indexOf("z")?
"gram" (indexes 3–6), 3, 10, and -1.
Why does name.trim(); on its own line not remove the spaces from name?
Strings are immutable. trim() (and the more modern strip()) returns a new string without the spaces, but the result is discarded. Write name = name.strip();.
A login check uses if (input == "admin"). It works in a quick test with a hard-coded string but fails for typed input. Why?
== compares object identity. The hard-coded test used the same pooled literal object, so == was true. Typed input is a new String object created at runtime, so == is false even though the text is identical. Use "admin".equals(input).
How do you safely check that a String s contains some non-whitespace text, even if s may be null?
s != null && !s.isBlank(). The null check must come first; && short-circuits so isBlank() is never called on null.
What does "2024-05-17".split("-") return, and how would you split "a.b.c" on the dots?
An array ["2024", "05", "17"]. For dots you must escape the regular-expression meaning of .: "a.b.c".split("\\.") gives ["a", "b", "c"]. split(".") would treat every character as a separator and return an empty array.
Previous: Java Switch Expressions: Arrow Labels, Multiple Labels, yield and case null
Next: The Java String API, Code Points, StringBuilder and Text Blocks
Related reading
- Java Switch Expressions: Arrow Labels, Multiple Labels, yield and case null
- Java Operators: Increment, Relational, Logical, Conditional, Bitwise and Precedence
- Java Type Conversion and Casting: Widening, Narrowing and Compound Assignment
- Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More
- Java Variables, Constants, var and final Explained

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.