Java - String replace() Method
The Java string replace() method returns the string where the specified character sequence is replaced with new character sequence in the given string.
Syntax
public String replace(CharSequence target, CharSequence replacement)
Parameters
target |
specify the character sequence to be replaced. |
replacement |
specify the character sequence to replace with. |
Return Value
Returns the replaced version of the specified string.
Exception
NA.
Example:
In the example below, replace() method returns the string where the substring World is replaced with new substring Java in the given string.
import java.lang.*; public class MyClass { public static void main(String[] args) { String MyString = "Hello World!"; String NewString = MyString.replace("World", "Java"); System.out.println(NewString); } }
The output of the above code will be:
Hello Java!
❮ Java.lang - String