Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

String replace()

The java string 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, allowing you to replace a sequence of char values.


There are two type of replace methods in java string.

  1. public String replace(char oldChar, char newChar)
  2. and
  3. public String replace(CharSequence target, CharSequence replacement)

The second replace method is added since JDK 1.5.


oldChar : old character

newChar : new character

target : target sequence of characters

replacement : replacement sequence of characters


replaced string

Java String replace(char old, char new) method example

  1. public class ReplaceExample1{
  2. public static void main(String args[]){
  3. String s1=Kreationnext is a very good website”;
  4. String replaceString=s1.replace(‘a’,‘e’);//replaces all occurrences of ‘a’ to ‘e’
  5. System.out.println(replaceString);
  6. }}

Java String replace(CharSequence target, CharSequence replacement) method example

  1. public class ReplaceExample2{
  2. public static void main(String args[]){
  3. String s1=“my name is khan my name is java”;
  4. String replaceString=s1.replace(“is”,“was”);//replaces all occurrences of “is” to “was”
  5. System.out.println(replaceString);
  6. }}
my name was khan my name was java