Java String Best Practices and Common Pitfalls

Top 10 Java String Best Practices

1. Use StringBuilder for Loops/Heavy Concatenation

// ✅ Efficient:  
StringBuilder sb = new StringBuilder();  
for (String s : list) sb.append(s);  

// ❌ Avoid:  
String result = "";  
for (String s : list) result += s;  

2. Always Compare Strings with equals()

if (str1.equals(str2)) { ... }  // ✅ Value check  
if (str1 == str2) { ... }       // ❌ Reference check  

3. Prefer String.isEmpty() Over length() == 0

if (input.isEmpty()) { ... }  // Cleaner and clearer  

4. Leverage String.join() for Simple Concatenation

String csv = String.join(", ", list);  // Cleaner than loops  

5. Sanitize User Input

String safe = userInput.replaceAll("[^a-zA-Z0-9]", "");  // Remove invalid chars  

6. Use try-with-resources for File I/O

try (BufferedReader br = Files.newBufferedReader(path)) { ... }  // ✅ Auto-closes  

7. Store Passwords in char[], Not String

char[] password = passwordField.getPassword();  // Safer in memory  

8. Specify Encoding for Bytes ↔ String Conversions

byte[] utf8Bytes = str.getBytes(StandardCharsets.UTF_8);  // ✅ Explicit  

9. Precompile Regex Patterns

private static final Pattern EMAIL_REGEX = Pattern.compile("...");  // ✅ Reusable  

10. Use Text Blocks (Java 15+) for Multi-Line Strings

String json = """  
             { "name": "Radha" }  
             """;  // Clean and readable  

7 Deadly Sins (Common Pitfalls)

❌ Using == for String Value Checks

if (new String("test") == "test") { ... }  // Always false!  

❌ Ignoring Locale in Case Conversions

"TITLE".toLowerCase();          // "title" (works in English)  
"TITLE".toLowerCase(Locale.TURKISH);  // "tıtle" (correct for Turkish)  

❌ Logging Sensitive Data

logger.info("Password reset: " + password);  // Exposes secrets in logs!  

❌ Uncontrolled String Concatenation in SQL

String query = "SELECT * FROM users WHERE name = '" + input + "'";  // SQLi risk!  

❌ Forgetting String Immutability

str.toUpperCase();  // Does nothing!  
str = str.toUpperCase();  // ✅  

❌ Using trim() for Unicode Whitespace

String s = "\u2000Hello\u2000";  
s.trim();   // ❌ Fails  
s.strip();  // ✅ Java 11+  

❌ Overusing String.intern()

// Can cause PermGen/metaspace leaks!  
String s = new String("text").intern();  // Only use after profiling  

FAQ

When to use StringBuffer over StringBuilder?

Only in legacy multi-threaded code (99% of cases use StringBuilder).

How to handle NullPointerException with Strings?

Use Objects.requireNonNull() or Optional:

String safe = Optional.ofNullable(input).orElse(“default”);

Why does "Hello".substring(0, 10) throw an error?

endIndex exceeds the string length. Always validate indices.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments