Retrieving the Last Character from Java Strings

Accessing the final character of a String in Java requires accounting for zero-based indexing. The most direct approach utilizes the charAt method combined with the length property:

String content = "Programming";
char terminal = content.charAt(content.length() - 1);
System.out.println(terminal); // Output: g

For scenarios requiring manipulation of the character sequence as an array, convert the string first:

String message = "Development";
char[] symbols = message.toCharArray();
char finalSymbol = symbols[symbols.length - 1];

When working with supplementary Unicode characters (those out side the Basic Multilingual Plane), a single char may not represent a complete logical character. In such cases, process code points instead:

String sequence = "Emoji 😀";
int finalCodePoint = sequence.codePointBefore(sequence.length());
String lastChar = new String(Character.toChars(finalCodePoint));

Alternatively, substring extraction provides another pathway, particularly useful when the result must remain a String object rather than a primitive char:

String input = "Algorithm";
String lastCharacter = input.substring(input.length() - 1);

Each approach offers distinct trade-offs. The charAt method provides optimal performance for ASCII and BMP text, while codePointBefore ensures correctness for internationalized applications containing emojis or rare scripts. Array conversion incurs additional memory overhead but enables batch processing of characters.

Tags: java String Manipulation Character extraction Unicode handling Text processing

Posted on Sun, 10 May 2026 10:26:57 +0000 by vallette