w3resource logo


Introduction to Java Programming

Java String: replace() Method

Secondary Nav

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

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 :







Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables