String replace example in java

This example shows you the use of different type of replace methods of String class

package com.java.connect.string;
 
// String replace example in java
public class StringReplaceExample {
    public static void main(String[] args) {
        //
        // declare the String with some text
        //
        String string = "Some text here to replace";
        //
        // The Java String class defines three methods to replace character
        // Or substring from the given Java String object.
        // String replace(int oldChar, int newChar)
        // This method replaces a specified character with new character
        // and returns a new string object.
        // String replaceFirst(String regularExpression, String newString)
        // Replaces the first substring of this string that matches
        // the given regular expression with the given new string.
        // String replaceAll(String regex, String replacement)
        // Replaces the each substring of this string that matches the given
        // regular expression with the given new string.
        //
 
        //
        // Replaces all occourances of given character with new one and returns new String object.
        //
        System.out.println("Replaced 'e' char with 'z' : "
                + string.replace('e', 'z'));
 
        //
        // Replaces only first occourances of given String with new one and returns new String object.
        //
        System.out.println("Replaced 'palce' string with 'here' : "
                + string.replaceFirst("place", "here"));
 
        //
        // Replaces all occourances of given String with new one and returns new String object.
        //
        System.out.println("Replaced all 'text' string with 'here' : "
                + string.replaceAll("text", "string"));
    }
}

The output of above example will be as:

Replaced 'e' char with 'z' : Somz tzxt hzrz to rzplacz
Replaced 'palce' string with 'here' : Some text here to rehere
Replaced all 'text' string with 'here' : Some string here to replace