Is there any quick way to get the last two characters in a string?

Solution 1:

The existing answers will fail if the string is empty or only has one character. Options:

String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;

or

String substring = str.substring(Math.max(str.length() - 2, 0));

That's assuming that str is non-null, and that if there are fewer than 2 characters, you just want the original string.

Solution 2:

theString.substring(theString.length() - 2)

Solution 3:

String value = "somestring";
String lastTwo = null;
if (value != null && value.length() >= 2) {  
    lastTwo = value.substring(value.length() - 2);
}

Solution 4:

Use substring method like this::

str.substring(str.length()-2);