Home
Java
String Right Part
Updated Sep 21, 2023
Dot Net Perls
String right. A string contains important characters on its end (the right side). With a custom method, we can easily extract these characters.
Method notes. Substring is often useful, but it can be hard to use. It requires a begin index and an optional end index. To implement right, we calculate the begin index.
Input and output. Consider a string like "website." When we take the right 4 chars, we are left with the string "site." Our method uses Substring to achieve this goal.
String substring
Right(4) Input = "website" Output = "site"
Example program. Right() calls substring in its implementation. It computes the beginning by subtracting the argument (the count of chars) from the string length.
Thus The call to right will extract the specified number of characters from the end of the string, and return it as a new string.
Result With an argument of 4, right() returns the last four chars of a string. With 7, it returns the last seven chars.
public class Program { public static String right(String value, int length) { // To get right characters from a string, change the begin index. return value.substring(value.length() - length); } public static void main(String[] args) { // Test the right method. String value = "website"; String result = right(value, 4); System.out.println(result); value = "Java Virtual Machine"; result = right(value, 7); System.out.println(result); } }
site Machine
A substring helper. A Java program can use substring directly whenever it is needed. But in my experience, helper methods, like right(), make programs easier to develop.
Other methods. Other methods, like between(), before and after, are similar to right. They get substrings near known syntax parts. These are perhaps even more useful.
String Between
A review. With right() we extract the rightmost part of a string. This utility method can make programs easier to develop (and understand afterwards). It is a substring-based method.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen