Top 10 Java StringBuilder Programs with Logic
1. Reverse a String using StringBuilder
Logic: Use StringBuilder's reverse() method.
Example:
StringBuilder sb = new StringBuilder("hello");
sb.reverse(); // Output: olleh
2. Check if a String is Palindrome using StringBuilder
Logic: Compare original string with reversed string using StringBuilder.
Example:
String str = "madam";
StringBuilder sb = new StringBuilder(str);
if(str.equals(sb.reverse().toString())) // It's a palindrome
3. Remove characters from a String
Logic: Use delete(start, end) to remove characters.
Example:
StringBuilder sb = new StringBuilder("abcdef");
sb.delete(2, 4); // Output: abef
4. Insert characters at a position
Logic: Use insert(index, string).
Example:
StringBuilder sb = new StringBuilder("HelloWorld");
sb.insert(5, " "); // Output: Hello World
5. Replace part of a string
Logic: Use replace(start, end, string).
Example:
StringBuilder sb = new StringBuilder("Hello Java");
sb.replace(6, 10, "World"); // Output: Hello World
6. Append multiple strings efficiently
Logic: Use append() to avoid + operator in loops.
Example:
StringBuilder sb = new StringBuilder();
Top 10 Java StringBuilder Programs with Logic
sb.append("Hello").append(" ").append("World"); // Output: Hello World
7. Find the length of a string using StringBuilder
Logic: Use length() method.
Example:
StringBuilder sb = new StringBuilder("hello");
int len = sb.length(); // Output: 5
8. Delete a character at specific index
Logic: Use deleteCharAt(index).
Example:
StringBuilder sb = new StringBuilder("hello");
sb.deleteCharAt(1); // Output: hllo
9. Convert StringBuilder to String
Logic: Use toString() method.
Example:
StringBuilder sb = new StringBuilder("hello");
String str = sb.toString();
10. Clear the contents of a StringBuilder
Logic: Use setLength(0) to clear.
Example:
StringBuilder sb = new StringBuilder("data");
sb.setLength(0); // Output: empty