How do I get the last character of a string?
Grab the last character of a Java string with charAt(length() - 1)
:
Decoding string length and index positioning
Java Strings
start counting from zero, a nod to our robot overlords. This makes the first character at index 0
, and the last character at length() - 1
. Java has given us the powerful charAt
method that caters to our needs of extracting a character at any particular index:
In-depth exploration: Alternative methods and edge cases
Digging into the substring
method
Like a Swiss Army knife, the substring
method has many uses. It's great when you want to extract not just a single last character, but perhaps a few from the back:
"Hey, my string is not an empty void!"
Before you dive into character extraction, ensure that the string is not empty. This will help prevent the scary StringIndexOutOfBoundsException
monster lurking in the dark cornerns of your code.
Slaying null
and empty strings
A well-armored solution should prevent both empty and null strings from busting your code:
endsWith
: the gatekeeper of suffixes
The endsWith
method is handy when you need to check if a string ends with a certain character:
takeLast
: the non-existent hero of last characters
A hypothetical takeLast
method could swoop in to grab multiple characters from the end of a string. Since Java hasn't introduced it yet, here's how you could do it on your own:
Was this article helpful?