Java .replace()
Published Apr 16, 2022
Contribute to Docs
The String class’ .replace() method returns a new string where all instances of a given value are switched with a new value.
Syntax
string.replace(char oldValue, char newValue);
A char represents a single character. Other valid inputs for the .replace() method include the following:
- An instance of the
Characterclass that resolves to a single character. - A
CharSequenceinterface that represents a sequence of characters (theStringclass is one implementation of this interface).
In any case, the returned result will always be a new String object with all instances of oldValue replaced with the newValue.
Example
The example below tests a string s with the usage of char values, Character instances, and a CharSequence where a substring, “Hello”, is replaced with “Goodbye” and reassigned:
public class ReplaceMe {public static void main(String args[]) {String s = "Hello World!";System.out.println("Original String: " + s);char testA = 'e';System.out.println("With primitive char: " + s.replace(s.charAt(2), testA));Character testB = new Character('o');System.out.println("With Character class: " + s.replace(s.charAt(6), testB));CharSequence testC = "Goodbye";System.out.println("With CharSequence: " + s.replace("Hello", testC));}}
This results in the following output:
Original String: Hello World!With primitive char: Heeeo Wored!With Character class: Hello oorld!With CharSequence: Goodbye World!
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours