Java String - replace() Method
The Java replace() method returns the string where the specified character or character sequence is replaced with new character or character sequence in the given string.
Syntax
public String replace(char searchChar, char newChar) public String replace(CharSequence target, CharSequence replacement)
Parameters
searchChar |
specify the character to be replaced. |
newChar |
specify the character to replace with. |
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 character 'l' is replaced with 'k' in the given string.
public class MyClass { public static void main(String[] args) { String MyString = "Hello World!"; String NewString = MyString.replace('l', 'k'); System.out.println(NewString); } }
The output of the above code will be:
Hekko Workd!
Example:
In the example below, replace() method returns the string where the substring World is replaced with new substring Java in the given string.
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 String Methods