String methods – replace

In this post, we will discuss about replace(),replaceFirst() and replaceAll. As it name says , method replace is used to replace a sequence of characters in a string with a expected characters or substring.

There are 4 types of implementations of replace.

  1. String replace(char oldChar, char newChar)
  2. String replace(CharSequence target,CharSequence replacement)
  3. String replaceFirst(String regex, String replacement)
  4. String replaceAll(String regex, String replacement)

Let’s understand them with examples.

String replace(char oldChar, char newChar):

This will replace the old character with a new character.

e.g. Take string “Wall” and replace char ‘w’ with char ‘b’. Look at the below example for result.

Output: Replace char w with b : ball

String replace(CharSequence target,CharSequence replacement):

This method will returns string after replacing a sequence of characters with the a new sequence of characters.

e.g. If we replace “aaa” with “bb” in the string “aaaa” , it will result “bba”.

Output: Replace char sequence aaa with bb : bba

String replaceFirst(String regex, String replacement):

It replaces the first substring of this string that matches the given regular expression with the expected substring.

e.g. In the example below, it will replace the whole string which comes after substring “bo”, with substring “house”.

Output: Replace string comes aftre bo : This is a house

String replaceAll(String regex, String replacement):

It replaces the all substrings of this string that matches the given regular expression with the expected substring.

Output: Replace substring ‘book cover’ with ‘house’ : This is a house and this house looks beautiful.
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
String methods - isEmpty() and lastIndexof
String methods - split()
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...