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. SignatureThere are two types of replace() methods in Java String class. The second replace() method is added since JDK 1.5. ParametersoldChar : old character newChar : new character target : target sequence of characters replacement : replacement sequence of characters Returnsreplaced string Exception ThrowsNullPointerException: if the replacement or target is equal to null. Internal implementationJava String replace(char old, char new) method exampleFileName: ReplaceExample1.java Test it NowOutput: jevetpoint is e very good website Java String replace(CharSequence target, CharSequence replacement) method exampleFileName: ReplaceExample2.java Test it NowOutput: my name was khan my name was java Java String replace() Method Example 3FileName: ReplaceExample3.java Output: oooooo-ssss-oooooo oooooo-hhhh-oooooo Java String replace() Method Example 4The 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) Next TopicJava String replaceAll() |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India