Home >>Java String Methods >Java String replace() Method

Java String replace() Method

Java String replace() Method

Java replace() method in Java String is used to searches a string for a specified character, and returns a new string where the specified character are replaced.

Syntax

public String replace(char searchChar, char newChar)

Parameters

searchChar - This parameter is used to represents A char the character that will be replaced by the new character

newChar - This parameter is used to represents A char the character to replace the searchChar with

Technical Details

Returns - It is used to return A new String, where the specified character has been replaced by the new character

Java String replace() Method Example 1


public class ReplaceExample1 
{
  public static void main(String[] args) 
  {
    String Name = "php";
    System.out.println(Name.replace('p', 'h'));
  }
}

Output:
hhh

Java String replace() Method Example 2


public class ReplaceExample2 
{  
    public static void main(String[] args) 
	{  
        String str1 = "kkkkk-lllll-mmmmm";  
        String rs = str1.replace("k","a"); 
        System.out.println(rs);  
        rs = rs.replace("m","c"); 
        System.out.println(rs);  
    }  
}  

Output:
aaaaa-lllll-mmmmm
aaaaa-lllll-ccccc

No Sidebar ads