In Java we often 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.
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
.
Input: apple Truncate(3): app
This program introduces the truncate()
method. It receives two parameters—the String
to truncate and the length of the desired String
.
if
-statement ensures that the substring()
method never receives a length that is too long. This avoids errors.string
, when the truncate-length is shorter than the String
itself.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); } }app apple apple
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.