Java replace() vs replaceAll() Method

Java replace() vs replaceAll() Method | Java has various methods and functions to manipulate strings. The replace() and replaceAll() methods are one of them. Even though both replace() and replaceAll() methods are used to replace characters or sub-string in the given string but they work differently. Let us see the difference between them.

The method details of both replace() and replaceAll() are as follows:-

  1. public String replace(char oldChar, char newChar)
  2. public String replace(CharSequence oldChar, CharSequence newChar)
  3. public String replaceAll(String oldChar, String newChar)

The replace() method can replace one character with another character or it can replace a CharSequence with another CharSequence. It can’t replace based on the regular expression. The replaceAll() method can only replace one string with another string, where the first string is a regular expression.

The main difference between replace() and replaceAll() is:- replaceAll() replaces based on the regular expression but replace() method doesn’t.

replace() vs replaceAll() Java

This program shows the working of the replace() method.

public class Main {
   public static void main(String args[]) {
      String str = "Java Language, Python Language, " + "Go Language";
      String str1 = str.replace("Language", "Program");
      String str2 = str.replace('a', 'e');
      System.out.println(str1);
      System.out.println(str2);
   }
}

Output:-

Java Program, Python Program, Go Program
Jeve Lenguege, Python Lenguege, Go Lenguege

This program shows the working of the replaceAll() method.

public class Main {
   public static void main(String args[]) {
      String str = "Java Program, Python Program, Go Program";
      String str1 = str.replaceAll("(.*)Program(.*)", "Language");
      String str2 = str.replaceAll("Program", "Language");
      System.out.println(str1);
      System.out.println(str2);
   }
}

Output:-

Language
Java Language, Python Language, Go Language

Java replace() vs replaceAll() Performance

As a performance concern, the replace() function is much faster than the replaceAll() method because replace() method first compiles the regular expression pattern and then matches and finally replaces the character.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *