replace() String Example

replace() String Example

java.lang.String class comes with replace() String method to replace existing characters in a sting with new characters.

The signature of replace() String as given in Java API.

  • public String replace(char oldChar, char newChar): Returns a new string after replacing characters. All the occurrences of oldChar in the string are replaced by newChar.

In the following example, each occurrence of A in str1 is replaced by K and a new string is returned. Original string str1 is not disturbed.

replace() String
Output screen on replace() String Example

Also refer for a similar method replaceFirst().

Pass your comments and suggestions on this tutorial "replace() String Example".

Leave a Reply

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