Write a program to Replace string with another string in java using String.replace() method


  • public class Replace_Method: This is the class declaration.
  • public static void main(String args[]): This is the main method that gets executed when the program runs. It takes a string array as an argument.
  • String str1="String Function";: This creates a string variable str1 and assigns it the value "String Function".
  • String str2="Java Exercises";: This creates a string variable str2 and assigns it the value "Java Exercises".
  • System.out.println("Strings Before Replacing .. ");: This prints the message "Strings Before Replacing .. " to the console.
  • System.out.println("string 1 : "+str1);: This prints the value of str1 concatenated with the string "string 1 : " to the console.
  • System.out.println("string 2 : "+str2);: This prints the value of str2 concatenated with the string "string 2 : " to the console.
  • str1=str1.replace(str1, str2); : This replaces the value of str1 with the value of str2.
  • System.out.println("\nStrings After Replacing .. ");: This prints the message "Strings After Replacing .. " to the console.
  • System.out.println("string 1 : "+str1);: This prints the value of str1 concatenated with the string "string 1 : " to the console.
  • System.out.println("string 2 : "+str2);: This prints the value of str2 concatenated with the string "string 2 : " to the console.

Source Code

public class Replace_Method
{
	public static void main(String args[])
	{
		String str1="String Function";
		String str2="Java Exercises";
 
		System.out.println("Strings Before Replacing .. ");
		System.out.println("string 1 : "+str1);
		System.out.println("string 2 : "+str2);
 
		//replacing string str1 with str2
		str1=str1.replace(str1, str2);
 
		System.out.println("\nStrings After Replacing .. ");
		System.out.println("string 1 : "+str1);
		System.out.println("string 2 : "+str2);
	}
}

Output

Strings Before Replacing ..
string 1 : String Function
string 2 : Java Exercises

Strings After Replacing ..
string 1 : Java Exercises
string 2 : Java Exercises

Example Programs