1. Introduction
In Java, replacing a substring within a string can be accomplished using the replace() or replaceAll() method. These methods are part of the String class and are used to replace all occurrences of a specified substring or pattern with a new string. In this guide, we will look at a simple Java program that demonstrates how to replace a substring within a given string.
2. Program Steps
1. Define a main method to serve as the entry point of the program.
2. Declare and initialize a String in which a substring will be replaced.
3. Call the replace() method on the initialized String, specifying the substring to be replaced and the replacement string.
4. Print the original String and the modified String to the console.
3. Code Program
public class ReplaceSubstringExample {
public static void main(String[] args) {
// Step 2: Declare and initialize a String in which a substring will be replaced
String originalString = "Java is a programming language.";
// Step 3: Call the replace() method, specifying the substring to be replaced and the replacement string
String modifiedString = originalString.replace("language", "platform");
// Step 4: Print the original String and the modified String to the console
System.out.println("Original String: " + originalString);
System.out.println("Modified String: " + modifiedString);
}
}
Output:
Original String: Java is a programming language. Modified String: Java is a programming platform.
4. Step By Step Explanation
– Step 1: The main method is defined as the entry point of the program.
– Step 2: A String named originalString is declared and initialized with the value "Java is a programming language."
– Step 3: The replace() method is called on originalString. The method takes two parameters: the substring to be replaced ("language") and the replacement string ("platform"). The modified string is stored in a new variable named modifiedString.
– Step 4: The originalString and the modifiedString are printed to the console to visualize the replacement of the substring.
This program illustrates the fundamental usage of the replace() method in Java for modifying strings by replacing substrings.