Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

How To Replace substring from a String in Java

In this post, we are going to replace a substring in a String in Java. A substring can be a single char or multiple chars of the String While String is a class in Java that represents a sequence of characters.

To replace the substring, we are using replace() and replaceFirst() method. The replace() method is used to replace a substring from a string and returns a string after modification.

The replaceFirst() method is used to replace the first occurrence of a substring from the string and returns a new String after modification.

Time for an Example:

Let's create an example to replace a single char occurrence from the whole string. Here, we are using the replace() method to replace 'a' with 'A' in the entire string.

public class Main {
	public static void main(String[] args){
		String str = "abracadabra";
		System.out.println(str);
		// Replace a char in String
		str = str.replace('a', 'A');
		System.out.println(str);
	}
}


abracadabra
AbrAcAdAbrA

Example: Replace using replace() Method

Let's create another example to replace a substring from the string. Here, we are using replace() method to replace all the occurrence of "ab" with "AB" from the whole string.

public class Main {
	public static void main(String[] args){
		String str = "abracadabra";
		System.out.println(str);
		// Replace substring in String
		str = str.replace("ab", "AB");
		System.out.println(str);
	}
}


abracadabra
ABracadABra

Example: Replace using replaceFirst() Method

In this example, we are using replaceFirst() method to replace the first occurrence of a substring in the string. It stops searching for a substring after the first match and returns a new string after replacing the substring.

public class Main {
	public static void main(String[] args){
		String str = "abracadabra";
		System.out.println(str);
		// Replace substring in String
		str = str.replaceFirst("ab", "AB");
		System.out.println(str);
	}
}


abracadabra
ABracadabra