Javatpoint Logo
Javatpoint Logo

Java String replace()

The Java String class replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence.

Since JDK 1.5, a new replace() method is introduced that allows us to replace a sequence of char values.

Signature

There are two types of replace() methods in Java String class.

The second replace() method is added since JDK 1.5.

Parameters

oldChar : old character

newChar : new character

target : target sequence of characters

replacement : replacement sequence of characters

Returns

replaced string

Exception Throws

NullPointerException: if the replacement or target is equal to null.

Internal implementation

Java String replace(char old, char new) method example

FileName: ReplaceExample1.java

Test it Now

Output:

jevetpoint is e very good website

Java String replace(CharSequence target, CharSequence replacement) method example

FileName: ReplaceExample2.java

Test it Now

Output:

my name was khan my name was java

Java String replace() Method Example 3

FileName: ReplaceExample3.java

Output:

oooooo-ssss-oooooo
oooooo-hhhh-oooooo

Java String replace() Method Example 4

The replace() method throws the NullPointerException when the replacement or target is null. The following example confirms the same.

FileName: ReplaceExample4.java

Output:

For learning Java, JavaTpoint is a very good site.
Exception in thread "main" java.lang.NullPointerException
	at java.base/java.lang.String.replace(String.java:2142)
	at ReplaceExample4.main(ReplaceExample4.java:12)






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA