Java String replace() method
Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence.
Syntax:
public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement)
Parameters:
oldChar : old Character
newChar : new Character
target : target sequence of characters
replacement: replacement sequence of characters
Returns:
a new String i.e. replaced Strin
Java String replace(char old, char new) method example 1
public class JavaStringReplaceEx1 { public static void main(String args[]) { String s1="W3lcom3 to the TutorialsAndExampl3"; String replaceString=s1.replace('3','e');//replaces all occurrences of '3' to 'e' System.out.println(replaceString); } }
Output:
Welcome to the TutorialsAndExample
Java String replace(CharSequence target, CharSequence replacement) method example 2
public class JavaStringReplaceEx2 { public static void main(String args[]) { String s1="Welcome to rock TutorialAndExample"; String replaceString=s1.replace("rock","the");//replaces all occurrences of "rock" to "the" System.out.println(replaceString); } }
Output:
Welcome to the TutorialAndExample
Java String replace method Example 3
public class JavaStringReplaceEx3 { public static void main(String[] args) { String str = "JABA IS THE BEST"; String rs = str.replace("JABA","JAVA"); System.out.println(rs); String str1 = rs.concat(" PROGRAMMING LANGUAGE"); System.out.println(str1); String rs2 = str1.replace("THE BEST","A OBJECT ORIENTED"); System.out.println(rs2); } }
Output:
JAVA IS THE BEST JAVA IS THE BEST PROGRAMMING LANGUAGE JAVA IS A OBJECT ORIENTED PROGRAMMING LANGUAGE
Java String replace method Example 4
public class JavaStringReplaceEx4 { public static void main(String[] args) { String a = "HelloBrother How are you!"; String r = a.replace("HelloBrother","Brother"); System.out.println(r); } }
Output:
Brother How are you!