×

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

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

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...

4 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Java String lastIndexOf() method

Java String lastIndexOf() method returns last index of character or substring in a String. Syntax: Method Description int lastIndexOf(int ch)It returns last index position for the given char valueint lastIndexOf(int ch, int...

2 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.