Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
HowToDoInJava
  • Java
  • Spring AI
  • Spring Boot
  • Hibernate
  • JUnit 5
  • Interview

Java String replace()

Java String replace() searches for a literal substring and replaces each occurrence with the replacement string beginning with index 0.

Lokesh Gupta

October 11, 2023

Java String class
Java String
Java String

The String.replace() API searches for a literal substring and replaces each occurrence with the replacement string. The search for substring starts from the beginning of the string i.e. index 0.

Note that a similar method String.replaceAll() searches and replaces all substrings using regular expressions.

1. String.replace() Method

The replace() method is an overloaded method and comes in two versions:

public String replace(char oldChar, char newChar);

public String replace(CharSequence target, CharSequence replacement);
  • The first method accepts the char types. It searches the string for specified oldChar and replaces each occurrence of oldChar with the newChar.
  • The second method accepts the String types. It searches the string for the specified target substring and replaces each occurrence with the replacement.

2. Replace All Occurrences of a Character

The following Java program replaces all occurrences of the letter ‘o’ (lower case) with the letter ‘O’ (upper case).

String message = "Hello world !!";

Assertions.assertEquals("HellO wOrld !!", message.replace('o', 'O'));

3. Replace All Occurrences of a Substring

The following Java program replaces all occurrences of the substring “Hello” with the new String “Hi”.

String message = "Hello world !!";

Assertions.assertEquals("Hi world !!", message.replace("Hello", "Hi"));

4. Regex is Not Supported

Regular expressions are not allowed as method arguments. If we use a regex pattern, it will be treated as a literal string.

In the following program, the regex [H] pattern will match character H is regex is supported. But replace() does not support regex so there are no matches found.

String message = "Hello world !!";

Assertions.assertEquals("Hello world !!", message.replace("[H]", "h"));

5. Null is Not Allowed

The 'null' is not allowed as both method arguments. It will throw NullPointerException.

Assertions.assertThrows(NullPointerException.class, () -> {
  message.replace(null, "O");
});

Assertions.assertThrows(NullPointerException.class, () -> {
  message.replace("o", null);
});

Happy Learning !!

References:
Java String Doc

Comments

Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

String Examples

  • String Constant Pool
  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • Align Left, Right, Center
  • Immutable Strings
  • StringJoiner
  • Split a string
  • Escape HTML
  • Unescape HTML
  • Convert to title case
  • Find duplicate words
  • Left pad a string
  • Right pad a string
  • Reverse recursively
  • Leading whitespaces
  • Remove whitespaces
  • Reverse words
  • Find duplicate characters
  • Get first 4 characters
  • Get last 4 characters
  • (123) 456-6789 Pattern
  • Interview Questions

String Methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

Table of Contents

  • 1. String.replace() Method
  • 2. Replace All Occurrences of a Character
  • 3. Replace All Occurrences of a Substring
  • 4. Regex is Not Supported
  • 5. Null is Not Allowed
Photo of author

Lokesh Gupta

A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies. An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Follow on Twitter Portfolio

Previous

Java String concat()

Next

Java String replaceFirst()

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

OOP

Regex

Maven

Logging

TypeScript

Python

Meta Links

About Us

Advertise

Contact Us

Privacy Policy

Our Blogs

REST API Tutorial

Follow On:

  • Github
  • LinkedIn
  • Twitter
  • Facebook
Copyright © 2026 | Sitemap