Replace() in Java - How to replace a character in a string

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

replace() in Java

This method replaces a character (or substring) in a string.

Syntax:

or

How to Call the Method:

or

Example:

If you run this code on your computer, you will see the following in the console:

Commentary:

Initially, there is a variable called oldString with the text "ABC". To replace 'A' with 'B', we used the replace() method.

  • As the first parameter, we set what we would like to replace. In this case it is the character 'A'
  • As the second parameter, we set what we would like to replace it with. In this case with the character 'B'

As a result, we've got a new string with the text "BBC".

Please note, that the first string (oldString) wasn't changed when we used the replace() method.  That means that the replace() method returned a new string. 

That's all. You can find more articles in our Java Tutorial for Beginners.

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr
Самоучители--узнать детальнее--