×

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example programs.

replace()

The replace() method of a Java String class returns a string that replaces every old char as well as CharSequence with a new char for CharSequence.

A new replace() function that has been available since JDK 1.5 enables us just to replace a series of char values.

If the replacement or target is equivalent to null, a NullPointerException will occur.

This method can be used for many purposes like replacing only the characters in a string, or replacing the sequence of characters in a string. Let us go through few example programs to understand.

Let’s us now understand the below program flow in which the replacement of single characters takes place.

File name: Replace1.java

public class Replace1{  
public static void main(String args[]){  
String s1="my name is Aiden Smith";  
String replaceString=s1.replace('m','o');//All m’s will be replaced with o.  
System.out.println(replaceString);  
}}  

Output

oy naoe is Aiden Soith

Now, let us understand the below example program that depicts the replacement of sequence of characters.

File name: Replace2.java

public class Replace2{ 

public class Replace2{  
public static void main(String args[]){  
String s1="my name is Aiden Smith my wife’s name  is Kenzie Madison";  
String replaceString=s1.replace("my","our");//my would be replaced with our
System.out.println(replaceString);  
}}  

Output

our name is Aiden Smith our wife’s name  is Kenzie Madison

When the replacements or target is null, the replace() method raises the NullPointerException. The below program depicts this.

File name: Replacenull.java

public class Replacenull   
{  
public static void main(String argvs[])  
{  
  
String str = "My friend is a good soccer player. He is a champion.";  
int size = str.length();  
  
System.out.println(str);  
String target = null;   
str = str.replace(target, "JavaTpoint ");  
System.out.println(str);  
  
}  
}  

Output

My friend is a good soccer player. He is a champion.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.toString()" because "target" is null
        at java.base/java.lang.String.replace(String.java:2954)
        at Replacenull.main(Replacenull.java:11)

replaceall()

The replaceAll() method of Java String class returns a string that replaces every sequence of characters that match the pattern and replacement string.

If the regular expression's syntax is incorrect, a PatternSyntaxException will occur.

Let us understand the replaceall() method by few simple example programs

Replaceall.java

public class Replaceall1{  
public static void main(String args[]){  
String s1="my wife name is kenzie madisson";  
String replaceString=s1.replaceAll("k","l");// All k’s are replaced by l.
System.out.println(replaceString);  
}}

Output

my wife name is lenzie madisson

Now, let us go through how the sequence of characters are replaced

File name: Replaceall2.java

public class Replaceall2{  
public static void main(String args[]){  
String s1="My name is Aiden. My wife name is Kenzie Madisson.";  
String replaceString=s1.replaceAll("Kenzie","Benzie");//replaces all occurrences of "is" to "was"  
System.out.println(replaceString);  
}}

Output

My name is Aiden. My wife name is Benzie Madisson. 

When there is an incorrect regular expression, the replaceAll() function throws the PatternSyntaxException. Check out at the example below.

File name: Replaceallnull.java

public class Replaceallnull   
{  
public static void main(String argvs[])  
{  
  
// input string  
String str = "Every Sunday is the end of the week.";  
  
System.out.println(str);  
  
String regex = "\\"; 
  
str = str.replaceAll(regex, "Sunday ");  
  
System.out.println(str);  
  
}  
}  

Output

Every Sunday is the end of the week.
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
        at java.base/java.util.regex.Pattern.error(Pattern.java:2038)
        at java.base/java.util.regex.Pattern.compile(Pattern.java:1799)
        at java.base/java.util.regex.Pattern.<init>(Pattern.java:1440)
        at java.base/java.util.regex.Pattern.compile(Pattern.java:1079)
        at java.base/java.lang.String.replaceAll(String.java:2938)
        at Replaceallnull.main(Replaceallnull.java:13)

The functional differences are

  • replace() replaces every instance of the old char with the new char, whereas replaceAll() replaces every instance of the old string with current string. This is the difference between the two methods. Basically, replace() replaces characters and replaces All() can replace individual characters in strings.
  • The String. replaceFirst() function and replaceAll() are equivalent. The only distinction amongst them is that for all instances where the sub-string appears in the string, the provided string is used in lieu of it.
  • A string can be replaced with a specific substring by employing the replace() and replaceAll() methods. Both approaches have the same names, but they operate in different ways.
  • replace() replaces every instance of the old char with the new char, whereas replaceAll() replaces every instance of the old string with new string. This is the difference between the two methods.

Related Topics

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.