User John Selawsky
John Selawsky
Senior Java Developer and Tutor at LearningTree

Java String replace() Method

Published in the Java Developer group

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

The String class provides four different kinds of replace() methods in Java. Each of the methods addresses a specific use case. Their names are listed below:
  1. replace(char, char)
  2. replace(String, String)
  3. replaceAll(String, String)
  4. replaceFirst(String, String)
Moving forward with the post, we will see how each method works. We’ll also look into the need of using the above in different use cases.

Java String replace() method

The Java String replace() method is used to replace a specified character with the given character both passed as parameters. This method is suitable for replacing any character in a String with some other character of your choice.

Method Header


public String replace(char oldCharacter, char newCharacter)

Method Parameters

The method takes two ‘char’ type parameters or arguments.
  • char oldCharacter holds the character to be replaced.

  • char newCharacter holds the character that will be used in place of the oldCharacter.

Return Type

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

Example

Let’s have a look at different simple examples to understand how this method works.

public class Driver {

	public static void main(String[] args) {

	      String myString = "An apple a day, keeps the doctor away!";
		System.out.println("Original Sentence: \t\t\t" + myString);

		// Example 1 using String replace(char, char)
		char oldCharacter = 'a'; // replacing character
		char newCharacter = 'A'; // character to be replaced
            String updatedString = myString.replace(oldCharacter, newCharacter);    
		System.out.println("After replacing '" + oldCharacter + "' with '" + 
		// 'a' is replaced and not with 'A' as the method is case sensitive
		newCharacter + "': \t\t" + updatedString);
		
		// Example 2 using String replace(String, String)
		String oldString = "apple";
		String newString = "orange";
		// using the method String replace		
            String updatedString1 = myString.replace(oldString, newString); 
            System.out.println("Replacing '" + oldString + "' with '" + 
        		newString + "': \t" + updatedString1 + "\n");
	}
}

Output

Original Sentence: An apple a day, keeps the doctor away! After replacing 'a' with 'A': An Apple A dAy, keeps the doctor AwAy! Replacing 'apple' with 'orange': An orange a day, keeps the doctor away!
Note: You’re advised to get acquainted with regular expressions aka regex before moving forward.

Java String replaceAll() method

The Java String replaceAll() method replaces EVERY single occurrence of a regular expression passed as a parameter with the desired String. This means, that every copy of regex is updated by the replacement string.

Method Header


public String replaceAll(String regularExpression, String replacementStr)

Method Parameters

This method takes two ‘String’ type arguments.
  • String regularExpression holds the regex (pattern) to be replaced.

  • String replacementStr is the String that will be used in place of the regex.

Return Type

The method returns a new string after replacing all occurrences of the regex.

Example

This method is commonly used to update huge data records. For a deeper understanding, let’s look at different examples of the replaceAll() method.

public class Driver1 {

	public static void main(String[] args) {

		String myString = "Mastering a programming language begins with great logic building!";
		System.out.println("Original Sentence: \t\t\t" + myString);

		String regex = "[\sa]"; // This regex is used to remove all spaces and a(s) in the string
		String replacementStr = "";
		// using the method String replaceAll(); to remove ALL spaces
		System.out.println("After replacing \"" + regex + "\" with \"" + replacementStr + "\": \t"
				+ myString.replaceAll(regex, replacementStr) + "\n");
	}
}

Output

Original Sentence: Mastering a programming language begins with great logic building! After replacing "[ a]" with "": Msteringprogrmminglngugebeginswithgretlogicbuilding!

Java String replaceFirst() method

The Java String replaceFirst() method replaces the ONLY FIRST occurrence of the regex passed to this method.

Method Header


public String replaceFirst(String regularExpression, String replacementStr)

Method Parameters

This method takes two ‘String’ type arguments.
  • String regularExpression holds the regex (pattern) to be replaced.

  • String replacementStr is the String that will be used in place of the regex.

Return Type

The method returns a new string after replacing only the FIRST occurrence of the regex.

Example

This method can be used when you want to update just the first record found of your matching argument. Let’s explore how it works in the example below.

public class Driver2 {
	
	public static void main(String[] args) {

		String myString = "Good Morning. You wonders of Nature. Today is a great day to be happy.";
		System.out.println("Original Sentence: \t\t" + myString);

		String regex = "\\."; // regex to update period / full stop
		String replacementStr = "!";
		// using the method String replaceFirst();
		// to remove first period(.) with exclamation(!) mark
		System.out.println("After replacing '" + regex + "' with '" + replacementStr + "': \t"
				+ myString.replaceFirst(regex, replacementStr));
	}
}

Output

Original Sentence: Good Morning. You wonders of Nature. Today is a great day to be happy. After replacing '\.' with '!': Good Morning! You wonders of Nature. Today is a great day to be happy.
Java String replace() Method - 1

Conclusion

So those were some basics of using the replace() methods in Java. As always, we highly recommend learning by practice. Until next time, keep learning and keep growing!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION