w3resource

Java String: replace() Method

public String replace(char oldChar, char newChar)

The replace() Method returns a string resulting from replacing all occurrences of oldChar in this string with newChar.

If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a String object is returned that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.

Java Platform: Java SE 8

Syntax:

replace(char oldChar, char newChar)

Parameters:

Name Description Type
oldChar the old character. String
newChar the new character. String

Return Value:a string derived from this string by replacing every occurrence of oldChar with newChar.

Return Value Type: char

Pictorial presentation of Java String replace() Method

Java String: replace() Method

Example: Java String replace(char oldChar, char newChar) Method

The following example shows the usage of java String() method.

public class Example {

public static void main(String[] args)
    {
        String str = "The quick brown fox jumps over the lazy dog.";

        // Replace all the 'd' characters with 'f' characters.
        String new_str = str.replace('d', 'f');
        System.out.println();
        // Display the strings for comparison.
System.out.println("Original string: " + str);
System.out.println("New String: " + new_str);
System.out.println();
    }
}

Output:

Original string: The quick brown fox jumps over the lazy dog.
New String: The quick brown fox jumps over the lazy fog.

Java Code Editor :

Previous:regionMatches Method
Next:replaceAll Method



Follow us on Facebook and Twitter for latest update.