Write a program to replace a specified character with another character


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_Char
{    
	public static void main(String[] args)
	{
		String str1 = "Java Exercise";		
		String str2 = str1.replace('e', 'Q');
 
		System.out.println("Given String : " + str1);
		System.out.println("After String Character Replace : " + str2);
	}
}

Output

Given String : Java Exercise
After String Character Replace : Java ExQrcisQ

Example Programs