What is the difference between the replace and replaceAll function? | Core Java Forum
Vikrant Feddewar Posted on 19/07/2021


I am trying to explore the string function but I dont see any difference between replace and replace all function?

Please explain

Yogesh Chawla Replied on 19/07/2021

replace method of String class replaces all occurrences of one character with another character in the given string. On the other hand, first argument of replaceFirst and replaceAll is regular expressions (regex) which we want to use for replacement.

See this:


public class ClassABC {

	public static void main(String args[]) {
		String str = new String("String is a Immutable Class");

		System.out.println("Statement replacing 'a' with 'p':");
		System.out.println(str.replace('a', 'p'));

		System.out.println("String replacing 'i' with 'k' :");
		System.out.println(str.replace('i', 'k'));

		System.out.println("String after replacing class with object :");
		System.out.println(str.replaceFirst("Class", "Object"));

		System.out.println("String after replacing String with Integer");
		System.out.println(str.replaceFirst("String", "Integer"));

		System.out.println("String after replacing all a with space ");
		System.out.println(str.replaceAll("a", " "));

		System.out.println("Replacing whole String: ");
		System.out.println(str.replaceAll("(.*)Class(.*)", "Immutable"));

		System.out.println("Original Value of str is intact - " + str);

Yogesh Chawla Replied on 19/07/2021

See this also:

public class ClassXYZ {
	public static void main(String[] args) {
		String myString = "__a___a___b";
		char oldChar = 'a';
		char newChar = 'o';
		System.out.println(myString.replace(oldChar, newChar));

		 * Replace all occurrences of the string fish with sheep.
		myString = "one fish, two fish, three fish";
		String target = "fish";
		String replacement = "sheep";

		System.out.println(myString.replace(target, replacement));

		 * Use replaceAll() if you want to use a regular expression pattern.
		 * Replace any number with an x.

		myString = "__1_6____3__6_345____0";

		String regex = "\\d";
		replacement = "x";

		System.out.println(myString.replaceAll(regex, replacement));
		System.out.println(myString.replaceFirst(regex, replacement));
		 * Remove all whitespace.
		myString = "   Horse         Cow\n\n   \r Camel \t\t Sheep \n Goat       ";
		regex = "\\s";
		replacement = "";
		System.out.println(myString.replaceAll(regex, replacement));