owned this note
owned this note
Published
Linked with GitHub
---
title: Java String replace() Method - Scaler Topics
description: In Java, we can replace occurrences of a character or substring using the replace() method. Learn more on Scaler topics.
category: Java
author: Bharat L. Vora
---
:::section{.main}
In Java, we can replace occurrences of a character or substring using the `replace()` method, which has two variations:
1. `replace(char oldChar, char newChar)`
2. `replace(CharSequence oldString, CharSequence newString)`
These methods return a new string with the replacements made. Note that the original string is not modified since strings in Java are immutable.
### Syntax
The `replace()` method in Java has two syntaxes.
* 1. Syntax for Replacing a Character:
```java
public String replace(char searchChar, char newChar)
```
* 2. Syntax for Replacing a Substring:
```java
string.replace(CharSequence oldString, CharSequence newString);
```
### Parameters Values
To replace all occurrences of a particular character with another character in Java, we use the first syntax of the replace() method in Java.
> 1. **`oldChar`** - The character to be replaced in the string.
> 2. **`newChar`** - The character to be used instead of oldChar in the string.
To replace all occurrences of a particular string or substring with another string or substring, we use the second syntax of the replace() method in java.
> 1. **`oldString`** - The string or substring to be replaced in the original string.
> 2. **`newString`** - The string or substring to be used in place of the old string or substring in the original string.
:::
:::section{.main}
### Return Value
The `replace()` method in Java returns a new string where each occurrence of a character/word/sentence has been replaced with a new character/word/sentence.
If there is no match for the new character/word/sentence, the `replace()` in java method returns the original string.
### Exception
We cannot use `null` as an argument in the `replace()` method. If we use `null` as an argument, the system will throw a `NullPointerException`.
### Internal Implementation
Here is the internal implementation of the replace method in java:
```java
public String replace(char oldChar, char newChar) {
// If the characters are not equal
if (oldChar != newChar) {
int len = value.length; // Length of the string
int i = -1; // Initialize index variable
char[] val = value; // Get the character array of the string
// Find the index of the first occurrence of oldChar
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
// If oldChar is found
if (i < len) {
char buf[] = new char[len]; // Create a new character array to store the modified string
// Copy characters from the original string until the index of oldChar
for (int j = 0; j < i; j++) {
buf[j] = val[j];
}
// Replace all occurrences of oldChar with newChar
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
// Return the new string created from the modified character array
return new String(buf, true);
}
}
// If oldChar is not found or oldChar equals newChar, return the original string
return this;
}
```
:::
:::section
## Java String replace() Method Examples
### Example 1: Java String replace(char old, char new) Method
Replacing One Character with Another in Java Using `replace()` in java.
```java
public class Main {
public static void main(String[] arg) {
System.out.println("Original String - G00d M0rning");
//replacing '0' with 'o' and displaying it on the screen.
System.out.println(
"Corrected String - " + "G00d M0rning".replace('0', 'o')
);
}
}
```
**Output:**
```java
Original String - G00d M0rning
Corrected String - Good Morning
```
In the above code, we display the string object "`G00d M0rning`" and then call the replace() method on this object. We replace '0' with 'o' and then print the modified string on the screen.
### Example 2: Java String replace(CharSequence target, CharSequence replacement) Method
Example of the `replace(CharSequence oldString, CharSequence newString)` method in Java:
```java
public class Main {
public static void main(String[] args) {
String originalString = "Hello, World!";
String newString = originalString.replace("World", "Java");
System.out.println("Original String: " + originalString);
System.out.println("Replaced String: " + newString);
}
}
```
**Output:**
```
Original String: Hello, World!
Replaced String: Hello, Java!
```
### Exception 3: Exception in Java replace() method
```java
public class Main {
public static void main(String[] arg) {
String obj = "Hello World";
try {
//replacing "World" with null and trying to store it again in 'obj'
obj = obj.replace("World", null);
//Displaying the replaced string
System.out.println(obj);
} catch (NullPointerException e) {
System.out.println("NullPointerException occurred!");
}
}
}
```
**Output**
```
NullPointerException occurred!
```
:::
:::section{.summary}
## Conclusion
- The `replace()` in java is a built-in method of the Java `String` class.
- It is utilized to replace characters or substrings within a string.
- If the replacement does not find a match, the original string remains unchanged and is returned as the result.
:::
:::section{.faq-section}
## Frequently Asked Questions (FAQs)
**Q**. What implementations are available for the replace() in Java String class?
**A**. There are various other built-in method implementations, such as:
* replaceFirst()
* replaceAll()
**Q**. Do replaceAll() and replace() work the same?
**A**. replaceAll() is an advanced implementation of replace() where regular expressions can be used to replace in java all occurrences of characters in a string.