Java String replace() example

In this guide, you will learn about the String replace() method in Java programming and how to use it with an example.

1. String replace() Method Overview


The replace() method of Java's String class is utilized to replace all the occurrences of a specified character or substring with another character or substring within the invoking string.


1. str.replace(char oldChar, char newChar)
2. str.replace(CharSequence target, CharSequence replacement)


- oldChar: the old character.

- newChar: the new character.

- target: the sequence of char values to be replaced.

- replacement: the replacement sequence of char values.

Key Points:

- Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

- The replace() method is case-sensitive.

- If the old character or substring is not found, the original string is returned.

- The method does not alter the original string but returns a new one.

2. String replace() Method Example

public class ReplaceExample {
    public static void main(String[] args) {
        String sample = "Java Programming Java";

        // Replacing a character
        String replaced1 = sample.replace('a', 'A');
        System.out.println("Replace 'a' with 'A': " + replaced1);

        // Replacing a substring
        String replaced2 = sample.replace("Java", "JAVA");
        System.out.println("Replace 'Java' with 'JAVA': " + replaced2);

        // Attempting to replace a non-existent character
        String replaced3 = sample.replace('z', 'Z');
        System.out.println("Replace 'z' with 'Z': " + replaced3);


Replace 'a' with 'A': JAvA ProgrAmming JAvA
Replace 'Java' with 'JAVA': JAVA Programming JAVA
Replace 'z' with 'Z': Java Programming Java


In the example:

1. We begin by replacing all occurrences of the character 'a' with 'A'. The replace() method alters every 'a' found in the string.

2. We then replace the substring "Java" with "JAVA". The method replaces each occurrence of the specified substring in the provided string.

3. Lastly, we attempt to replace a character that doesn't exist in the string ('z'). The method returns the original string unaltered.

Related Java String Class method examples