Last Updated:

An example of using the replace method in Java. How do I replace a character in a string?

replace method in java
 

A Brief Overview of the Replace Method in Java

In Java, there are several variations of the method that are used to replace a character, substring, or part of a string that satisfies a regular expression.replace

  • When there is a change in a row object, the result of the change is a new row.
  • If there are no changes to the input string, the original object is returned.

How does the replace method work?

In Java, the replace method works as follows: it is called on a line and the first parameter takes the character that you want to replace, the second parameter is what you want to replace the character in the first parameter. The method call will return a new line with the result of the substitution or the same line if what needed to be replaced was not found in the original line:

Let's see a fragment of the program:

The result of running the above code snippet is to print a new line to the console with all the capital letters 'P'.

It should also be noted that the replace method is case sensitive.

A method overload is a method in which substrings can be used instead of single characters.

replace (char charToReplace, char replacementChar)

replace (CharSequence targetToMatch, CharSequence replacement)

Variations of the replace method:

  • Learn more about the replaceAll() method.
  • Learn more about why a new line is created instead of modifying an existing line.
  • Learn more about working with strings.