BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java String replace(), replaceFirst() and replaceAll() methods

Last Updated: September 16, 2022 by Chaitanya Singh | Filed Under: java

In this tutorial, we will discuss replace(), replaceFirst()and replaceAll() methods. All of these Java String methods are mainly used for replacing a part of String with another String.

Java String replace method signature

  • String replace(char oldChar, char newChar): It replaces all the occurrences of a oldChar character with newChar character. For e.g. "pog pance".replace('p', 'd') would return dog dance.
  • String replaceFirst(String regex, String replacement): It replaces the first substring that fits the specified regular expression with the replacement String. PatternSyntaxException if the specified regular expression(regex) is not valid.
  • String replaceAll(String regex, String replacement): It replaces all the substrings that fits the given regular expression with the replacement String.

Java String replace() Method example

In the following example we are have a string str and we are demonstrating the use of replace() method using the String str. We have replaced all the occurrences of char ‘o’ with char ‘p’. In the second print statement we have replaced all the occurrences of char ‘i’ with the char ‘K’.

Here we are displaying the modified string using print statements but we didn’t actually changed the string str, to achieve that we need to assign the returned string of replace() method in a string and then that string can have the permanent changes.

public class JavaExample{
  public static void main(String args[]){
    String str = new String("Site is BeginnersBook.com");

    System.out.print("String after replacing all 'o' with 'p' :" );
    System.out.println(str.replace('o', 'p'));

    System.out.print("String after replacing all 'i' with 'K' :" );
    System.out.println(str.replace('i', 'K'));
  }
}

Output:
Java String replace method example

Java String replaceFirst() Method example

In the following example we are demonstrating the use of replaceFirst() method. This method replaces the part of a string with a new specified string. The difference between replaceFirst() and replaceAll() method is that the replaceFirst() replaces the first occurrence while replaceAll() replaces all the occurrences.

public class JavaExample{
  public static void main(String args[]){
    String str = new String("Site is BeginnersBook.com");

    System.out.print("String after replacing com with net :" );
    System.out.println(str.replaceFirst("com", "net"));

    System.out.print("String after replacing Site name:" );
    System.out.println(str.replaceFirst("Beginners(.*)", "XYZ.com"));
  }
}

Output:
Java String replaceFirst() method example

Java String replaceAll() Method Example

In the following example we are using replaceAll() method to replace all the occurrences of a given substring with the new string.

The difference between replace() and replaceAll() method is that the replace() method replaces all the occurrences of old char with new char while replaceAll() method replaces all the occurrences of old string with the new string. Basically replace() works with replacing chars and replaceAll() works with replacing part of strings.

public class JavaExample{
  public static void main(String args[]){
    String str = new String("My .com site is BeginnersBook.com");
    System.out.print("String after replacing all com with net: " );
    System.out.println(str.replaceAll("com", "net"));
		
    System.out.print("Replacing whole String: " );
    System.out.println(str.replaceAll("(.*)Beginners(.*)", "Welcome"));
  }
}

Output:
Java String replaceAll() method example

Case-insensitive replaceAll()

In the above example, we saw a case sensitive replace. We can do a case insensitive replace like this:

public class JavaExample
{
  public static void main(String args[])
  {

    String str = "Hello Ram, hello Steve";

    String repStr =
            str.replaceAll("Hello", "Hi");

    //(?i) is for the case insensitive replace
    String repStr2 =
            str.replaceAll("(?i)hello", "Hi");

    System.out.println("Input string: " + str);
    System.out.println("Case sensitive replaceAll: " + repStr);
    System.out.println("Case insensitive replaceAll : " + repStr2);
  }
}

Output:
Case insensitive replaceaAll of strings

Recommended Posts

  • Java Program to remove all whitespaces from a string
  • Java String matches() method
  • Java String contains() method
  • Java String join() method
❮ Java String

Top Related Articles:

  1. Java StringBuilder length()
  2. StringBuilder append() null values as “null” String
  3. Java String substring() Method with examples
  4. Java StringBuilder charAt()
  5. Java 8 Lambda Comparator example for Sorting List of Custom Objects

Tags: Java-Strings

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Chenna Harish says

    September 24, 2015 at 12:36 PM

    i want apostrophe like ‘gugjhg’ and jhjhh’dd these type of insertion in database using string.replace() method in java

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap