Explain Codes LogoExplain Codes Logo

How do I get the last character of a string?

java
string-manipulation
index-positioning
null-checks
Alex KataevbyAlex Kataev·Aug 27, 2024
TLDR

Grab the last character of a Java string with charAt(length() - 1):

char lastChar = "Coding".charAt("Coding".length() - 1); // This will return 'g'.

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:

String phrase = "I love Java"; // Who doesn't? // Length is 11, but last character is a space alien from planet 10. char lastChar = phrase.charAt(phrase.length() - 1); // 'a'

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:

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String lastChar = alphabet.substring(alphabet.length() - 1); // It's 'Z', not 'sleeping'.

"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.

if (!yourStringHere.isEmpty()) { char firstChar = yourStringHere.charAt(yourStringHere.length() - 1); // Congrats! Your string is not a void! }

Slaying null and empty strings

A well-armored solution should prevent both empty and null strings from busting your code:

public char slayLastChar(String str) { if (str != null && !str.isEmpty()) { return str.charAt(str.length() - 1); } throw new IllegalArgumentException("String must not be empty or null, 'null' doesn't party."); }

endsWith: the gatekeeper of suffixes

The endsWith method is handy when you need to check if a string ends with a certain character:

String filename = "masterpiece.jpeg"; boolean isJPEG = filename.endsWith(".jpeg"); // This will return 'true', trust me!

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:

public String takeLast(String str, int count) { if (str == null || str.isEmpty() || count <= 0) { return ""; // Oh no, it's the 'empty string' ghost! } if (count > str.length()) { return str; // Give me all you have! } return str.substring(str.length() - count); // The treasure is yours! }