Sub topic 6
Strings
This chapter covers the Apex String type: how it behaves, how equality works, and the methods you will use most. It assumes you can declare variables, know what null means, and have run anonymous Apex in the Developer Console or an IDE.
What a String is in Apex
A String is a sequence of characters. Literals use single quotes only. Double quotes are a syntax error.
String greeting = 'Hello, Apex';
String quote = 'It\'s fine';
String twoLines = 'line one\nline two';
System.debug(greeting.length());
System.debug(quote);Inside a literal, a backslash escapes the next character. Common escapes are \' for a single quote, \\ for a backslash, \n for a newline, and \t for a tab.
Strings are immutable. Methods such as toUpperCase() return a new string and leave the original unchanged. If you ignore the return value, nothing happens.
String name = 'acme';
name.toUpperCase();
System.debug(name);
name = name.toUpperCase();
System.debug(name);The first debug prints acme. The second prints ACME.
Null versus empty
A String that was never assigned is null. An empty string '' is a real string with length 0. They are different values, and calling a method on null throws a System.NullPointerException.
String note;
System.debug(note == null);
String empty = '';
System.debug(empty.length());
System.debug(String.isBlank(note));
System.debug(String.isEmpty(empty));Two static helpers cover the common cases:
| Method | `null` | `''` | `' '` (spaces) | `'x'` |
|---|---|---|---|---|
| `String.isEmpty(s)` | true | true | false | false |
| `String.isBlank(s)` | true | true | true | false |
Use String.isBlank for user input, because whitespace-only values are usually as useless as empty ones. Both helpers accept null safely, so you do not need a separate null check first.
Equality: case-insensitive `==`
This is the most common surprise for developers coming from Java. In Apex, == on strings ignores case. It is also null-safe, so null == null is true and comparing a string to null never throws.
String a = 'apex';
String b = 'APEX';
System.debug(a == b);
System.debug(a.equals(b));
System.debug(a.equalsIgnoreCase(b));This prints true, false, true. The equals method is case-sensitive. Because equals is called on an object, it throws a NullPointerException if the left side is null.
| Expression | Case-sensitive | Safe if left side is null |
|---|---|---|
| `a == b` | No | Yes |
| `a.equals(b)` | Yes | No |
| `a.equalsIgnoreCase(b)` | No | No |
The === operator is a different thing. In Apex it tests exact equality for objects, and for strings it compares exactly, including case. Use equals or == for ordinary string comparison, and reserve this behavior for cases where you need strict matching.
Ordering comparisons (<, >) on strings also ignore case. This can surprise you when sorting. If you need case-sensitive ordering, use compareTo, which is case-sensitive and returns a negative number, zero, or a positive number.
System.debug('apple' < 'BANANA');
System.debug('apple'.compareTo('BANANA'));The first line prints true. The second prints a positive number, because lowercase letters sort after uppercase in a case-sensitive comparison.
Concatenation and formatting
The + operator joins strings. If either operand is a String, the other is converted to text.
Integer count = 5;
String msg = 'Count: ' + count;
System.debug(msg);
System.debug(1 + 2 + ' items');
System.debug('items: ' + 1 + 2);The last two lines print 3 items and items: 12. Evaluation goes left to right, so the order of operands decides whether numbers are added or joined as text. Put parentheses around arithmetic inside a concatenation.
For larger messages, String.format fills numbered placeholders, and String.join combines a collection with a separator.
String text = String.format('{0} has {1} contacts', new List<Object>{ 'Acme', 12 });
System.debug(text);
List<String> parts = new List<String>{ 'a', 'b', 'c' };
System.debug(String.join(parts, ', '));In String.format, a single quote is special and swallows placeholders, so avoid apostrophes in the pattern. Write Acme has instead of Acme's.
Common methods
Most string work uses a small set of methods. All of them return new values.
| Method | Purpose | Example result |
|---|---|---|
| `length()` | Number of characters | `'abc'.length()` is 3 |
| `substring(start, end)` | Part of a string, end exclusive | `'abcdef'.substring(1, 4)` is `bcd` |
| `indexOf(s)` | First position, or -1 | `'hello'.indexOf('l')` is 2 |
| `contains(s)` | Is a substring present | `'hello'.contains('ell')` is true |
| `startsWith(s)`, `endsWith(s)` | Prefix and suffix tests | |
| `replace(a, b)` | Replace literal text | |
| `trim()` | Remove leading and trailing whitespace | |
| `split(regex)` | Break into a `List<String>` | |
| `toLowerCase()`, `toUpperCase()` | Change case |
String csv = ' red, green ,blue ';
List<String> colors = csv.split(',');
for (String c : colors) {
System.debug('[' + c.trim() + ']');
}
System.debug('abcdef'.substring(1, 4));
System.debug('hello'.indexOf('z'));split takes a regular expression, not a plain separator. Characters such as ., |, and + have special meaning there. To split on a literal dot, write split('\\.'). The contains, startsWith, and endsWith methods are case-sensitive, even though == is not. substring throws a System.StringException if the indexes are out of range, so check length() first when the input is not under your control.
Strings in the wider type system
A String is the most common target for conversion. Any primitive can be turned into text with String.valueOf, and text can be parsed back with methods such as Integer.valueOf. A String can hold an Id value, and an 18-character Id assigns to an Id variable directly. Strings have a heap cost, since each concatenation inside a loop creates a new object. For many appends in a loop, collect pieces in a List<String> and call String.join once.
The flow below summarizes how to pick an equality check.
Common mistakes
- Expecting
==to be case-sensitive, so'Admin' == 'admin'passes a check you meant to fail. - Calling
.equalsor.trim()on a variable that may benull. - Ignoring the return value of an immutable method such as
replace. - Passing a plain separator such as
'|'tosplitand getting unexpected results. - Using
isEmptywhere whitespace-only input should also be rejected.
Exercise
What do these two lines print, and why? System.debug('Total: ' + 2 + 3); and System.debug(2 + 3 + ' total');
Show answer
The first prints Total: 23 and the second prints 5 total. Evaluation is left to right. In the first line the leading string makes each + a concatenation. In the second line 2 + 3 is added as integers before the string is joined.
Exercise
Given String s = null;, which of these throws a NullPointerException: s == 'x', s.equals('x'), String.isBlank(s)?
Show answer
Only s.equals('x') throws, because it calls a method on null. The == operator and String.isBlank both handle null safely.
Exercise
Write code that splits the string 'a.b.c' on the dot and prints the number of parts.
Show answer
System.debug('a.b.c'.split('\\.').size()); prints 3. The dot must be escaped because split takes a regular expression, where an unescaped dot matches any character.