CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > String > Java String Manipulation: Replace, Split, and Join

Java String Tutorial

  • Introduction to String
  • String Immutability
  • Common Methods
  • String Comparison
  • Formatting in String
  • Performance Optimization
  • String Manipulation
  • Java Regex Example
  • Special Characters in String
  • String Security
  • Java 8+ String Enhancements
  • Internationalization
  • Advanced Java String Techniques
  • Java String Best Practices

Java String Manipulation: Replace, Split, and Join

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 3 min read · 0 Comments
Share: in X

Table of Contents

  • 1. Replacing Text
    • replace(): Simple Character/String Replacement
    • replaceAll() & replaceFirst(): Regex-Based Replacement
  • 2. Splitting Strings
    • split(String regex): Divide a String into an array using regex.
  • 3. Joining Strings
    • String.join() (Java 8+): Concatenate elements with a delimiter.
  • 4. Converting Between Types
    • String ↔ char[]
    • String ↔ byte[] (with Encoding)
    • Other Conversions
  • Common Mistakes
  • FAQ
    • Why does replaceAll(“\\d”, “X”) replace all digits?
    • How to split by whitespace?
    • Is String.join() better than StringBuilder for small lists?

1. Replacing Text

replace(): Simple Character/String Replacement

Replace all occurrences of a character or literal substring:

String text = "apple-banana-orange";  
String replaced = text.replace("-", ", ");  
// "apple, banana, orange"  

replaceAll() & replaceFirst(): Regex-Based Replacement

  • replaceAll(String regex, String replacement): Replace all regex matches.
String data = "Error: 404; Error: 500";  
String cleaned = data.replaceAll("Error: \\d+", "OK");  
// "OK; OK"  
  • replaceFirst(String regex, String replacement): Replace only the first match.
String log = "[WARN] Disk full. [WARN] Low memory.";  
log = log.replaceFirst("\\[WARN\\]", "[INFO]");  
// "[INFO] Disk full. [WARN] Low memory."  

Key Difference:

  • replace() works with literals.
  • replaceAll()/replaceFirst() use regex (slower for simple cases).

2. Splitting Strings

split(String regex): Divide a String into an array using regex.

String csv = "Java,Python,C++,JavaScript";  
String[] langs = csv.split(", ");  // ["Java", "Python", "C++", "JavaScript"]  

Handling Special Characters: Escape regex symbols like ., |, or $:

String path = "file.name.txt";  
String[] parts = path.split("\\.");  // ["file", "name", "txt"]  

Limiting Splits: Optional limit parameter restricts the number of splits:

String data = "one:two:three:four";  
String[] result = data.split(":", 2);  // ["one", "two:three:four"]  

3. Joining Strings

String.join() (Java 8+): Concatenate elements with a delimiter.

List<String> list = Arrays.asList("Java", "C#", "Python");  
String joined = String.join(" | ", list);  // "Java | C# | Python"  

Use Case: Building CSV lines or URLs:

String[] params = {"sort=asc", "page=2"};  
String url = "https://api.com/data?" + String.join("&", params);  

4. Converting Between Types

String ↔ char[]

// String to char[]  
char[] chars = "Hello".toCharArray();  

// char[] to String  
String s = new String(chars);  

String ↔ byte[] (with Encoding)

// String to UTF-8 bytes  
byte[] bytes = "text".getBytes(StandardCharsets.UTF_8);  

// byte[] to String  
String restored = new String(bytes, StandardCharsets.UTF_8);  

Other Conversions

// String to int  
int num = Integer.parseInt("42");  

// int to String  
String s = Integer.toString(42);  // or String.valueOf(42)  

Caution: Handle NumberFormatException for invalid parses.

Common Mistakes

❌ Forgetting Immutability:

String s = "hello";  
s.replace("h", "H");  // Original unchanged!  
s = s.replace("h", "H");  // ✅  

❌ Unescaped Regex in split():

"a|b|c".split("|");  // Incorrect! Splits every character.  
"a|b|c".split("\\|");  // ✅ ["a", "b", "c"]  

FAQ

Why does replaceAll("\\d", "X") replace all digits?

\\d is a regex pattern for digits. Use replace() for literal replacements.

How to split by whitespace?

Use split("\\s+") to handle multiple spaces/tabs.

Is String.join() better than StringBuilder for small lists?

Yes – it’s concise and optimized under the hood.

Related Posts:

  • Java String Best Practices and Common Pitfalls
  • Java Regex Tutorial: Pattern, Matcher, and Practical…
  • Arrays of Primitive Types in Java
  • Java StringBuilder: Why and How to Use It Efficiently
  • Arrays in Java
  • List in Java
Tags:javalanguage-fundamentalsString
Was this article helpful?
← Previous ArticleJava String Performance: Optimize Concatenation with StringBuilder
Next Article →Java Regex Tutorial: Pattern, Matcher, and Practical Examples

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap