Java String replace() Method

The replace() method searches for a given character in a string and returns a new string where the given characters are replaced. In this method, a new string is returned when new ones replace occurrences of old characters.

What are the common replace() methods of the String class in Java?

The String class provides four different kinds of replace() methods in Java. Each method solves a specific use case.

Their names are given below:

replace (char, char)
replace(string, string)
replace all(string, string)
replaceFirst(string, string)

Java String replacement() method

The Java String replace() method replaces the specified character with the given character, both passed as parameters. This method is suitable for replacing any character in a string with another character of your choice.

Method headers

public String replace(oldCharacter, character newCharacter).

Method parameters:

The method takes two parameters or arguments of type “char”.

  • char oldCharacter contains the character to be replaced.
  • char newCharacter contains the character that will be used instead of the old character.

Return type:

The String replace method returns the updated string after replacing the required character.

Example:

Let’s look at various simple examples to understand how this method works.

public class Driver {
public static void main(String[] args) {
System.out.println("Original sentence: \t\t\t" + my string);
char oldCharacter = 'a'; 
char newCharacter = 'A'; 
            String updatedString = myString.replace(oldCharacter, NewCharacter);
system.out.println("After replacing '" + oldCharacter + "' with '" 
newCharacter + "': \t\t" + updatedString);
String oldString = "apple";
String newString = "orange";
            String updatedString1 = myString.replace(oldString, newString);
            System.out.println("Replacing '" + oldString + "' with '" +
        newString + "': \t" + updatedString1 + "\n");
}
}

Output:
After replacing all o with T: WelcTme tT techvidvan

1. NullPointerException

The replace() method does not accept the regular expression null, it throws a NullPointerException.

import java.io.*;
class techvidvan {
public static void main(String[] args)
{
String str = "techvidvan";
int size = str.length();
System.out.println(str);
String target = null;
str = str.replace(target, "GFG");
System.out.println(str)Exception in thread "main" java.lang.NullPointerException
    at java.base/java.lang.String.replace(String.java:2142)
    at techvidvan.main(techvidvan.java:12);
}
}

Output:
ExException in thread “main” java.lang.NullPointerException
at java.base/java.lang.String.replace
at GFG.main

Example for Java String replace():

public class techvidvan {
public static void main(String args[])
{
String Str = new String("Welcome to techvidvan");
System.out.print("Original string: ");
System.out.println(Str);
System.out.print(
System.out.println(
Str.replaceFirst("techvidvan", "ASTHA"));
}
}

Output:
Original String: Welcome to techvidvan
After replacing 1st occurrence of regex with replace_str : Welcome to ASTHAfortechvidvan.

Replace the substring:

The chef informed us that he wanted to update the name of the ham sandwich to the Ham Deluxe to reflect the addition of new ingredients.

Aclass Replace techvidvan {
public static void main(String[] args) {
String ham_entry = "Ham: $3.00.";
String new_ham_entry = ham_entry.replace("Ham", "Ham Deluxe");
System.out.println(new_ham_entry);
}
}

Output:
Ham Deluxe: $3.00.

Let’s break down our code. First, we define a class called ReplaceSandwiches that holds the code for our program. We then declare a variable called ham_entry that stores the name of the ham sandwich and its price.

To replace the word “ham” in a ham_entry string with Ham Deluxe, we use Replace() method. The new_ham_entry variable is assigned the result of the replace() method. In conclusion, the contents of new_ham_ entry are printed in our program into the console. We now have an updated entry for the ham sandwich.

Replace character

The replace() method can also replace a single character with another character. Instead of appearing as Ham, we wrote Hom. We know that there is only one o in our string and we want to replace it with a.

We could use the following code to fix our error:

class techvidvan {
public static void main(String[] args) {
String ham_entry = "Ham Deluxe: $3.00.";
String new_ham_entry = ham_entry.replace("o", "a");
System.out.println(new_ham_entry);
}
}

Output:
Original String: Welcome to techvidvan
After replacing 1st occurrence of regex with replace_str : Welcome to ASTHAfortechvidvan.

Our program works just like our previous example, but this time, we’re replacing one character rather than a series of characters. In this case, we’ve replaced the o with the o.

Replace multiple instances. A new character or substring replaces each instance of a character or substring by the replace() method. For example, given that our string contains just one instance of the substring and character, we’ve substituted it with a single instance. But if there were several instances of a character or substring, all these would be substituted for them. Suppose we have a string that stores the text that will appear on a banner telling customers that the restaurant.

Program:

class techvidvan {
public static void main(String[] args) {
String new_banner = ham_entry.replace("MENU", "Sal's Kitchen");
System.out.println(new_banner);
}
}

Output:
Sal’s Kitchen
Come see the new menu!
Sal’s Kitchen.

Our code works just like our previous examples. However, since our initial string contains the word MENU twice, the replace() method replaces both instances. It’s worth noting that the lowercase word menu also appears in our string, but since replace() is case sensitive, it’s not replaced.

Advantages

  • The ease of use: Using and manipulating the strings is simple. It is also possible to concatenate, slice and reverse them. It also comes with easy and intuitive syntax, allowing programmers at all levels of expertise to use it. Compatibility: Strings are commonly used in programming, making them a common data type. It means that strings can be easily exchanged among different systems and platforms, which gives them high reliability and efficiency in communicating and sharing data.
  • Compatibility: Strings are the most common data type because they can be used in various programming languages. This makes transferring them from one system or platform to another easy, making them reliable and effective for data exchange and sharing.

Disadvantages

  • Mutability: In many programming languages, strings are immutable and cannot be changed after creation. Working with large or complex strings that require frequent changes may be disadvantageous because they can lead to inefficiencies and memory bottlenecks.
  • Memory consumption: Strings may consume too much memory when working on big strings or a lot of strings. This may be a problem in environments with limited memory, e.g., embedded systems or portable devices.

Conclusion

The replace() method is used in Java to replace each instance of a particular character or substring with another character or substring. This tutorial discussed how to use replace() to replace single characters, substrings, and multiple instances of a character or substring. We’ve also explored some detailed examples of the replace() method in action.

You are now equipped with the information you need to use the replace() function in Java to replace the contents of a string like a pro!