Write a program to replace each substring of a given string


This Java program replaces all occurrences of a given character in a String with another character using the replace() method and prints the resulting String.

The program defines a public class named "Replace_Char" with a main method that takes no arguments. The main method declares a String variable str1 with the value "Java Exercise".

Then, the program uses the replace() method of the String class to replace all occurrences of the character 'e' in str1 with the character 'Q' and stores the resulting String in the variable str2.

Finally, the program prints out the original String str1 and the resulting String str2 using the System.out.println method.

Source Code

public class Replace_SubString
{    
	public static void main(String[] args)
	{
		String str1 = "String and String Function";
		String str2 = str1.replaceAll("String", "Java");
		System.out.println("Given String : " + str1);
		System.out.println("After String Replace : " + str2);
	}
}

Output

Given String : String and String Function
After String Replace : Java and Java Function

Example Programs