TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java Truncate String

Implement a truncate method for the String class. Check 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.Strings
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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf