Java String replace() Method Example

1. Introduction

The JavaString.replace() method is used to replace each occurrence of a specified character or substring in a string with another character or substring. This method is helpful for modifying strings, such as formatting text or cleaning data. This tutorial will demonstrate how to use thereplace() method.

Key Points

-replace() can replace characters or substrings within a string.

- It returns a new string with replacements made, leaving the original string unchanged.

- This method is case-sensitive.

2. Program Steps

1. Declare a string that contains characters or substrings to be replaced.

2. Use thereplace() method to replace a specific character.

3. Use thereplace() method to replace a specific substring.

4. Print the results of the replacements.

3. Code Program

public class StringReplaceExample {    public static void main(String[] args) {        // Original string        String str = "Hello, world! Welcome to Java. Java is fun!";        // Replace all occurrences of 'a' with 'x'        String replacedChars = str.replace('a', 'x');        // Replace all occurrences of "Java" with "Kotlin"        String replacedSubstrings = str.replace("Java", "Kotlin");        // Print the results        System.out.println("Original string: " + str);        System.out.println("After replacing 'a' with 'x': " + replacedChars);        System.out.println("After replacing 'Java' with 'Kotlin': " + replacedSubstrings);    }}

Output:

Original string: Hello, world! Welcome to Java. Java is fun!After replacing 'a' with 'x': Hello, world! Welcome to Jxvx. Jxvx is fun!After replacing 'Java' with 'Kotlin': Hello, world! Welcome to Kotlin. Kotlin is fun!

Explanation:

1.String str = "Hello, world! Welcome to Java. Java is fun!": Declares and initializes aString variablestr.

2.String replacedChars = str.replace('a', 'x'): Uses thereplace() method to change all occurrences of the character 'a' to 'x'.

3.String replacedSubstrings = str.replace("Java", "Kotlin"): Uses thereplace() method to change all occurrences of the substring "Java" to "Kotlin".

4. The print statements display the original string, the string after character replacement, and the string after substring replacement.


Comments