Why not just String substr = word.substring(word.length() - 3)?

Update

Please make sure you check that the String is at least 3 characters long before calling substring():

if (word.length() == 3) {
  return word;
} else if (word.length() > 3) {
  return word.substring(word.length() - 3);
} else {
  // whatever is appropriate in this case
  throw new IllegalArgumentException("word has fewer than 3 characters!");
}
Answer from Egor on Stack Overflow
🌐
Reactgo
reactgo.com › home › how to get last n characters of a string in java
How to get last n characters of a string in Java | Reactgo
March 25, 2023 - String name = "piano"; String lastThree = name.substring(name.length()-3); System.out.println(lastThree); ... Note: The extraction begins at index 2, and extract the rest of the string.
🌐
Baeldung
baeldung.com › home › java › java string › get last n characters from a string
Get Last n Characters From a String | Baeldung
July 6, 2024 - From this String, we want to extract the year. In other words, we want just the last four characters, so, n is: ... We can use an overload of the substring() method that obtains the characters starting inclusively at the beginIndex and ending exclusively at the endIndex:
🌐
Dirask
dirask.com › posts › Java-get-last-3-characters-from-string-pzordj
Java - get last 3 characters from string
The below example shows how to use substring() method to get the last 3 characters from the text string. ... public class StringUtils { public static String getLastCharacters(String text, int charactersCount) { int length = text.length(); int ...
🌐
javaspring
javaspring.net › blog › get-the-last-three-chars-from-any-string-java
How to Get Last Three Characters from a String in Java: Resolving getChars Buffer and Index Confusion — javaspring.net
Math.max(0, length - 3) ensures beginIndex is 0 for strings shorter than 3 characters, so substring(0) returns the entire string. substring() is concise, readable, and optimized in Java (no extra object creation in modern JVMs for small substrings). For developers learning string manipulation, manually fetching characters with charAt() and building a result is educational. This method iterates from the start of the last three characters to the end of the string, collecting characters into a StringBuilder.
🌐
w3resource
w3resource.com › java-exercises › basic › java-basic-exercise-68.php
Java - Four copies of the last 3 characters of a string
February 2, 2026 - import java.lang.*; public class ... characters four times and print the result System.out.println(last_three_chars + last_three_chars + last_three_chars + last_three_chars); } }...
🌐
TutorialsPoint
tutorialspoint.com › How-to-extract-the-last-n-characters-from-a-string-using-Java
How to extract the last n characters from a string using Java?
February 20, 2020 - To extract last n characters, simply print (length-n)th character to nth character using the charAt() method. Example
Find elsewhere
Top answer
1 of 12
70

Why has nobody given the obvious answer?

sed 's/.*\(...\)/\1/'

… or the slightly less obvious

grep -o '...$'

Admittedly, the second one has the drawback that lines with fewer than three characters vanish; but the question didn’t explicitly define the behavior for this case.

2 of 12
58

Keeping it simple - tail

We should not need a regular expression, or more than one process, just to count characters.
The command tail, often used to show the last lines of a file, has an option -c (--bytes), which seems to be just the right tool for this:

$ printf 123456789 | tail -c 3
789

(When you are in a shell, it makes sense to use a method like in the answer of mikeserv, because it saves starting the process for tail.)

Real Unicode characters?

Now, you ask for the last three characters; That's not what this answer gives you: it outputs the last three bytes!

As long as each character is one byte, tail -c just works. So it can be used if the character set is ASCII, ISO 8859-1 or a variant.

If you have Unicode input, like in the common UTF-8 format, the result is wrong:

$ printf 123αβγ | tail -c 3
�γ

In this example, using UTF-8, the greek characters alpha, beta and gamma are two bytes long:

$ printf 123αβγ | wc -c  
9

The option -m can at least count the real unicode characters:

printf 123αβγ | wc -m
6

Ok, so the last 6 bytes will give us the last 3 characters:

$ printf 123αβγ | tail -c 6
αβγ

So, tail does not support handling general characters, and it does not even try (see below): It handles variable size lines, but no variable size characters.

Let's put it this way: tail is just right for the structure of the problem to solve, but wrong for the kind of data.

GNU coreutils

Looking further, it turns out that thee GNU coreutils, the collection of basic tools like sed, ls, tail and cut, is not yet fully internationalized. Which is mainly about supporting Unicode.
For example, cut would be a good candidate to use instead of tail here for character support; It does have options for working on bytes or chars, -c (--bytes) and -m (--chars);

Only that -m/--chars is, as of version
cut (GNU coreutils) 8.21, 2013,
not implemented!

From info cut:

`-c CHARACTER-LIST'
`--characters=CHARACTER-LIST'
     Select for printing only the characters in positions listed in CHARACTER-LIST.  
     The same as `-b' for now, but internationalization will change that.


See also this answer to Can not use `cut -c` (`--characters`) with UTF-8?.

🌐
w3resource
w3resource.com › java-exercises › basic › java-basic-exercise-84.php
Java - Add the 3 characters at both sides of the string
import java.util.*; import java.io.*; ... } // Get the subpart of the string from the last 3 characters String subpart = string1.substring(string1.length() - 3); // Print the result, which is the subpart followed by the original ...
🌐
How to do in Java
howtodoinjava.com › home › string › get last 4 chars of a string in java
Get Last 4 Chars of a String in Java
January 18, 2023 - String input = "123456789"; String lastFourChars = ""; if (input.length() > 4) { lastFourChars = input.substring(input.length() - 4); } else { lastFourChars = input; } If data is in not in string form, first use the String.valueOf() method to convert it to String. Include the latest version of Apache commons lang from the Maven repo. <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency> The StringUtils.right() method gets the rightmost n characters of a String.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-string-substring
Master Java Substring Method: Examples, Syntax, and Use Cases | DigitalOcean
Learn how to use the Java substring method. Explore syntax, practical examples, and common errors to handle substrings effectively.
Top answer
1 of 3
1

I think you should create a new list to storage the sub string. Do you know when your for-cycle break? I debugged it and get that it will break when your alist.size()=0. The exception causes when the aList.get(i).length()<3. So you just do like this:

`
        List<String> aList = new ArrayList<String>();
        aList.add("4:78:34");
        aList.add("5:8:34");
        aList.add("8:18:90");
        aList.add("2:8:40");
        List<String> subList = new ArrayList<String>();
        for (int i = 0; i < aList.size(); i++)
        {

            String str = aList.get(i).substring(0, aList.get(i).length() - 3);
            subList.add(str);

        }
        System.out.println(subList);`
2 of 3
0

I worked up a recursive function for you to call to get the string after the right most colon. So if you can find another colon, it keeps looking further. If it can't it returns what's left.

public static String getRight(String str) {
    if (str.indexOf(':') > 0) {
        str = getRight(str.substring(str.indexOf(':')+1));
    }

    return str;
}

As PM 77-1 said, you are adding more items to your list so it can't ever get to the end of the list. You need to store the original count if you are to ever get out of your for loop. Here is your fully modified code tested and working:

public class SplitString {
    public static void main(String[] args) {

        List<String> aList = new ArrayList<String>();
        aList.add("4:78:34");
        aList.add("5:8:34");
        aList.add("8:18:90");
        aList.add("2:8:40");

        int original_size = aList.size();
        for(int i=0;i<original_size;i++){
            String str = aList.get(i);
            aList.add(getRight(str));
        }
        System.out.println(aList);
    }

    public static String getRight(String str) {
        if (str.indexOf(':') > 0) {
            str = getRight(str.substring(str.indexOf(':')+1));
        }

        return str;
    }
}
🌐
Sololearn
sololearn.com › en › Discuss › 2156592 › how-to-write-the-last-3-characters-of-a-string-variable-in-new-variable
How to write the last 3 characters of a string variable in new ...
February 3, 2020 - lastExternalReferrerTimeDetects how the user reached the website by registering their last URL-address. Maximum Storage Duration: PersistentType: HTML Local Storage · _fbpUsed by Facebook to deliver a series of advertisement products such as real time bidding from third party advertisers. Maximum Storage Duration: 3 monthsType: HTTP Cookie
🌐
Techie Delight
techiedelight.com › home › java › get last n characters from a string in java
Get last n characters from a String in Java | Techie Delight
July 7, 2026 - This post will discuss how to get the last n characters from a string in Java. To get the rightmost n characters of a string, you can use the right() method offered by the StringUtils class from Apache Commons Lang.
Top answer
1 of 3
3

That piece of code does exactly the opposite of what you want. Now let's see why and how we can modify it.

Quick solution

You can modify the code as follows to do what you want:

 String lastNchars = s.substring( Math.max(0, s.length()-n));

Explanation

According to the official documentation, Java String class has a special method called substring(). The signature of the method is the following (with overload):

 public String substring(int beginIndex, int endIndex))
 public String substring(int beginIndex)

The first method accepts 2 parameters as input:

  1. beginIndex: the begin index of the substring, inclusive.
  2. endIndex: the end index of the substring, exclusive.

The second overload will automatically consider as endIndex the length of the string, thus returning "the last part"

Both methods return a new String Object instance according to the input parameters just described.

How do you pick up the right sub-string from a string? The hint is to think at the strings as they are: an array of chars. So, if you have the string Hello world you can logically think of it as:

[H][e][l][l][o][ ][w][o][r][l][d]
[0]...............[6]......[9][10]

If you choose to extract only the string world you can thus call the substring method giving the right "array" indexes (remember the endIndex is exclusive!):

 String s = "Hello world";
 s.substring(6,11);

In the code snippet you provided, you give a special endIndex:

 Math.min(s.length(), n);

That is exactly up to the n th char index taking into account the length of the string (to avoid out of bound conditions).

What we did at the very beginning of this answer was just calling the method and providing it with the beginning index of the substring, taking into account the possible overflow condition if you choose a wrong index.

Please note that any String Object instance can take advantage of this method, take a look at this example, for instance:

 System.out.println("abc");
 String cde = "cde";
 System.out.println("abc" + cde);
 String c = "abc".substring(2,3);
 String d = cde.substring(1, 2);

As you see even "abc", of course, has the substring method!

2 of 3
2

Try,

String upToNCharacters = s.substring(s.length()-lastCharNumber);
🌐
C# Corner
c-sharpcorner.com › article › how-can-i-get-last-characters-of-a-string-in-java
How Can We Get Last Characters Of A String In Java?
December 29, 2025 - In this article, we will learn about String in Java Programming Language with examples. Explore the intricacies of Java strings, covering their creation using literals or the "new" keyword. Learn methods like charAt() to extract the last character, ensuring a comprehensive understanding through examples.