Retrieve a substring from the end in Java

To extract a substring in Java, use the substring method of the String class. By specifying the start index as the length of the original string minus the length of the substring, you can extract a substring from the end of the string.

Source Code


/**
 * Function to extract a substring from the end of a string
 *
 * @param str The original string
 * @param length The length of the substring to extract
 * @return The extracted substring
 * @throws IllegalArgumentException if str is null or if length exceeds the length of the string
 */
public static String substringFromEnd(String str, int length) {
	if (str == null) {
		throw new IllegalArgumentException("The string is null.");
	}

	if (str.length() < length) {
		throw new IllegalArgumentException("The specified length exceeds the length of the string.");
	}

	return str.substring(str.length() - length);
}

Test Code


import java.util.*;

public class Main {
	public static void main(String[] args) throws Exception {
		System.out.println(substringFromEnd("abcdefg", 3)); // Output: "efg"
	}

	/**
	 * Function to extract a substring from the end of a string
	 *
	 * @param str The original string
	 * @param length The length of the substring to extract
	 * @return The extracted substring
	 * @throws IllegalArgumentException if str is null or if length exceeds the length of the string
	 */
	public static String substringFromEnd(String str, int length) {
		if (str == null) {
			throw new IllegalArgumentException("The string is null.");
		}

		if (str.length() < length) {
			throw new IllegalArgumentException("The specified length exceeds the length of the string.");
		}

		return str.substring(str.length() - length);
	}
}

Follow me!

photo by:Jonas Jacobsson