HomeSearch

Java Truncate String

This Java example program implements a truncate method for the String class. It checks String length before using substring.
Truncate. Often we need to ensure a maximum length of Strings. We truncate strings to a length, making Strings that are too long shorter. No built-in method is available.
With substring, we can compose a helpful method to truncate strings. A logical branch, needed to eliminate exceptions, is helpful. This ensures more cases work correctly.
An example. This program introduces the truncate() method. It receives two parameters—the String to truncate and the length of the desired String.

If: The if-statement ensures that the substring() method never receives a length that is too long. This avoids errors.

If

Optimization: The method does nothing, returning the original string, when the truncate-length is shorter than the String itself.

Java program that implements truncate method public class Program { public static String truncate(String value, int length) { // Ensure String length is longer than requested size. if (value.length() > length) { return value.substring(0, length); } else { return value; } } public static void main(String[] args) { String test = "apple"; // ... Truncate to 3 characters. String result1 = truncate(test, 3); System.out.println(result1); // ... Truncate to larger sizes: no exception occurs. String result2 = truncate(test, 10); System.out.println(result2); String result3 = truncate(test, 5); System.out.println(result3); } } Output app apple apple
In the tests, the truncate() method works correctly on sizes that are too long (10). It successfully applies substring() to create a 3-char string.
Helpful methods, like truncate, are often key to developing more complex programs. Using an abstraction like truncate() makes a more complicated method easier, and clearer, to write.
For performance, truncate() avoids creating strings when possible. It does nothing when no new String is needed. This may help program performance.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls