The codePointBefore() method returns the Unicode code point that appears immediately before a given index. It is the backward-looking companion to codePointAt() and is essential when you walk a string from right to left or need the character just left of a cursor position.
01
Before Index
Looks backward, not forward.
02
Returns int
Full Unicode code point.
03
Index 1–length()
Different valid range.
04
Surrogate Pairs
Emoji handled correctly.
05
Reverse Walk
Parse from the end.
06
vs codePointAt()
Forward vs backward.
Fundamentals
Definition and Usage
In Java, codePointBefore(int index) is defined on java.lang.String. Picture each index as a gap between characters: index 0 is before the first character, index 1 is between the first and second, and so on. The method returns the code point of the character to the left of that gap.
For the string "Java", codePointBefore(1) returns the code point for 'J' (74), and codePointBefore(4) returns 'a' (97) because index 4 sits at the end of the word, immediately after the final letter.
💡
Beginner Tip
The valid range for codePointBefore() is 1 through length()—not the same as charAt(), which uses 0 through length() - 1. Calling codePointBefore(0) always throws an exception because nothing exists before the start of the string.
Foundation
📝 Syntax
The codePointBefore() method is declared in the String class:
java
public int codePointBefore(int index)
Parameters
index — the position after the character you want. Must be between 1 and length() inclusive.
Return Value
Returns the Unicode code point (as an int) of the character that ends immediately before the given index.
Exceptions
Throws StringIndexOutOfBoundsException if index is less than 1 or greater than the string length.
Cheat Sheet
⚡ Quick Reference
String
Call
Result
"Java"
codePointBefore(1)
74 ('J')
"Java"
codePointBefore(4)
97 ('a')
"Java😀"
codePointBefore(6)
128512 (emoji U+1F600)
"Java"
codePointBefore(0)
StringIndexOutOfBoundsException
"Java"
codePointBefore(5)
StringIndexOutOfBoundsException
First char
str.codePointBefore(1)
Character at index 0
Last char
str.codePointBefore(str.length())
Final code point
Forward peer
str.codePointAt(i)
Reads from index forward
Step back
i -= Character.charCount(cp)
Reverse loop advance
Hands-On
Examples Gallery
These programs run in Java 8+. They show basic lookups, emoji handling, comparison with codePointAt(), and safe backward iteration.
📚 Getting Started
Read the first and last characters using codePointBefore().
Example 1 — Code Point Before Index 1
Index 1 sits right after the first character, so codePointBefore(1) returns the opening letter.
java
public class CodePointBeforeExample {
public static void main(String[] args) {
String text = "Java";
int first = text.codePointBefore(1);
int last = text.codePointBefore(text.length());
System.out.println("Before index 1: " + first + " ('" + (char) first + "')");
System.out.println("Before end: " + last + " ('" + (char) last + "')");
}
}
📤 Output:
Before index 1: 74 ('J')
Before end: 97 ('a')
How It Works
codePointBefore(1) looks left of index 1 and finds 'J' at position 0. codePointBefore(4) looks left of the end-of-string gap and finds the final 'a'.
Example 2 — Character Before a Middle Index
In "Hello, Java!", index 7 sits at the letter J. The code point before index 7 is the space at index 6.
java
public class BeforeMiddleIndex {
public static void main(String[] args) {
String str = "Hello, Java!";
int index = 7;
int cp = str.codePointBefore(index);
System.out.println("Code point before index " + index + ": " + cp);
System.out.println("Character: '" + (char) cp + "'");
}
}
📤 Output:
Code point before index 7: 32
Character: ' '
How It Works
Index 7 marks the start of 'J'. Looking backward from that gap lands on the space character (Unicode 32) at index 6—not on 'J' itself. Use codePointAt(7) when you want the character at index 7.
📈 Practical Patterns
Emoji, method comparison, and reverse iteration.
Example 3 — Emoji String (Fixed from Original Tutorial)
The string "Java😀" has length 6 in UTF-16 units. The code point before index 4 is the last letter a; before index 6 is the full emoji.
java
public class EmojiBefore {
public static void main(String[] args) {
String text = "Java\uD83D\uDE00"; // "Java" + grinning face emoji
System.out.println("Length: " + text.length());
System.out.println("Before index 4: " + text.codePointBefore(4)
+ " ('" + (char) text.codePointBefore(4) + "')");
System.out.println("Before index 6: " + text.codePointBefore(6)
+ " (U+" + Integer.toHexString(text.codePointBefore(6)).toUpperCase() + ")");
}
}
📤 Output:
Length: 6
Before index 4: 97 ('a')
Before index 6: 128512 (U+1F600)
How It Works
Index 4 is where the emoji begins, so the character before it is 'a' (97)—not 'J' as a mislabeled comment in some older examples suggested. Index 6 is past the emoji, so codePointBefore(6) merges the surrogate pair and returns 128512.
Example 4 — codePointBefore() vs codePointAt()
Same string, same index number—but the two methods look in opposite directions.
java
public class BeforeVsAt {
public static void main(String[] args) {
String word = "Code";
int index = 2;
int before = word.codePointBefore(index);
int at = word.codePointAt(index);
System.out.println("codePointBefore(" + index + "): " + before
+ " ('" + (char) before + "')");
System.out.println("codePointAt(" + index + "): " + at
+ " ('" + (char) at + "')");
}
}
At index 2, codePointBefore reads the character to the left ('C' at index 1), while codePointAt reads the character starting at index 2 ('o'). Same index, different direction.
Example 5 — Walk Backward by Code Point
Decrement the index by Character.charCount(cp) to move left safely through emoji and BMP text.
java
public class ReverseCodePoints {
public static void main(String[] args) {
String text = "Go😀";
for (int i = text.length(); i > 0; ) {
int cp = text.codePointBefore(i);
System.out.println("Before index " + i + ": " + cp);
i -= Character.charCount(cp);
}
}
}
📤 Output:
Before index 5: 128512
Before index 3: 111
Before index 2: 71
How It Works
Start at length() and call codePointBefore(i) repeatedly. Subtract Character.charCount(cp) from i so the next step lands on the previous full character, skipping the middle of surrogate pairs.
Applications
🚀 Common Use Cases
Reverse parsing — read tokens or digits from the end of a string toward the start.
Text editor logic — find the character immediately left of a caret (cursor) position.
Backspace simulation — determine which code point would be deleted when the user presses Backspace.
International text — move backward through emoji and non-BMP characters without splitting surrogate pairs.
Pairing with codePointAt() — inspect characters on both sides of a split or delimiter index.
🧠 How codePointBefore() Works
1
You pass an index
Java receives the string and an index from 1 to length().
Input
2
Bounds are validated
Index 0 or values beyond length() throw StringIndexOutOfBoundsException.
Validate
3
Look at index − 1
If that code unit is a low surrogate, Java steps back to the high surrogate and returns the combined supplementary code point.
Backward
=
🌐
int code point
The full Unicode character that ends just before your index.
Important
📝 Notes
Valid indexes are 1 through length(), unlike charAt() which starts at 0.
codePointBefore(0) is always invalid—there is no character before the beginning.
The index refers to UTF-16 code unit positions, not byte offsets in a file.
Supplementary characters (emoji, rare scripts) are handled correctly by checking surrogate pairs backward.
Throws StringIndexOutOfBoundsException (not a generic IndexOutOfBoundsException message you must guess from).
Performance
⚡ Optimization
codePointBefore() runs in constant time (O(1)) for a single lookup. For scanning an entire string backward, pair it with Character.charCount() rather than decrementing by 1 each time. For bulk forward processing, prefer codePoints() or a forward loop with codePointAt(). No special optimization is needed for occasional backward reads.
Wrap Up
Conclusion
The codePointBefore() method completes the Unicode indexing toolkit alongside codePointAt(). It lets you read the character to the left of any gap in the string, with correct handling of emoji and supplementary characters.
Remember the index range difference: start at 1, end at length(). Practice the reverse-walk example until backward stepping with Character.charCount() feels natural—it prevents subtle bugs in internationalized applications.
Step backward with Character.charCount(cp) in loops
Pair with codePointAt() to inspect both sides of a gap
Validate index on user-supplied cursor positions
Learn codePointAt() first, then add backward reads
❌ Don’t
Call codePointBefore(0)—it always fails
Reuse charAt() index rules without adjusting for the +1 range
Decrement by 1 blindly when moving left through emoji text
Confuse “before index” with “at index”
Assume length() is a valid index for codePointAt() (it is for codePointBefore() only)
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about codePointBefore()
Use these points when reading characters backward in Java strings.
5
Core concepts
⏪01
Looks Backward
Before the index gap.
Purpose
🔢02
Index 1–length()
Not zero-based start.
Range
😀03
Emoji Safe
Surrogate-aware backward.
Unicode
🔄04
vs codePointAt()
Opposite direction.
Compare
📈05
Reverse Loops
Use charCount() to step.
Pattern
❓ Frequently Asked Questions
codePointBefore(int index) returns the Unicode code point that ends immediately before the given index. Think of index as a cursor position— the method tells you which character sits to the left of that cursor.
Call it on any String: string.codePointBefore(index). It takes one int parameter—the index measured in UTF-16 code units, same as charAt() and codePointAt().
index must be between 1 and length() inclusive. index 1 returns the first character; index length() returns the last character. index 0 or index greater than length() throws StringIndexOutOfBoundsException.
codePointAt(index) returns the code point starting at index (looking forward). codePointBefore(index) returns the code point ending before index (looking backward). They use the same index numbering but read in opposite directions.
If the code unit at index - 1 is a low surrogate, Java looks back to the matching high surrogate and returns the full supplementary code point—just like codePointAt() handles pairs when looking forward.
Use it when you iterate backward through a string, parse text from right to left, or need the character immediately before a cursor or split position—especially with international text and emoji.