GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Java Tutorial
  • Advanced Java
  • Interview Questions
  • Exercises
  • Examples
  • Quizzes
  • Projects
  • Cheatsheet
  • DSA in Java
  • Java Collection
  • Introduction3 min read
  • Variables2 min read
  • Data Types7 min read
  • Operators7 min read

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — String replace() method in Java with Examples - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • Java Tutorial
  • Advanced Java
  • Interview Questions
  • Exercises
  • Examples
  • Quizzes
  • Projects
  • Cheatsheet
  • DSA in Java
  • Java Collection

String replace() method in Java with Examples

Last Updated : 16 Feb, 2024

The String replace() method returns a new string after replacing all the old characters/CharSequence with a given character/CharSequence.

Example:

Return a new string where all " o" characters are replaced with "p" character:

Java
// Java program to demonstrate
// the replace() method

public class Main {
    public static void main(String[] args) {
        // Define an original string
        String originalString = "Hello World";

        // Replace 'o' with 'p' in the original string
        String replacedString = originalString.replace("o", "p");

        // Print the replaced string
        System.out.println(replacedString);
    }
}

Output
Hellp Wprld

Syntax

public String replace(char oldch, char newch)

Parameters

  • oldch: the old character.
  • newch: the new character.

Return Value

  • It returns a string derived from this string by replacing every occurrence of oldch with newch.

Exception

  • NullPointerException- replace() method returns this exception when the target char/CharSequence is null.

Java String replace() Examples

The following examples demonstrate how to use the replace() method in Java: 

Example 1: Java String replace(char old, char new) Method

To show the working of replace(char old, char new).

Java
// Java code to demonstrate the
// working of replace()

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

        // Initialising String
        String Str = new String("Welcome to geeksforgeeks");

        // Using replace to replace characters
        System.out.print("After replacing all o with T : ");
        System.out.println(Str.replace('o', 'T'));

        // Using replace to replace characters
        System.out.print("After replacing all e with D : ");
        System.out.println(Str.replace('e', 'D'));
    }
}

Output
After replacing all o with T : WelcTme tT geeksfTrgeeks
After replacing all e with D : WDlcomD to gDDksforgDDks

Example 2: Java String replace(String target, String replacement) Method

We can implement the replace() method with substring/CharSequence just like with char.

To show the working of the replace(String target, String replacement) method.

Java
// Java Program to implement
// replace() method
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        String s1 = "GeeksforGeeks";

        // orignal string
        System.out.println(s1);

        // Replace Geeks with Gfg
        String replaceString = s1.replace("Geeks", "GfG ");

        // New String
        System.out.println(replaceString);
    }
}

Output
GeeksforGeeks
GfG forGfG 

Example 3:

The null regular expression is not accepted by the replace() method, it raises the NullPointerException.

Java
// Java Program to implement
// Java replaceAll() method
import java.io.*;

// Driver Class
class GFG {
    // Main function
    public static void main(String[] args)
    {
        String str = "GeeksforGeeks";
        int size = str.length();

        System.out.println(str);
        String target = null;

        // replacing null with GFG
        str = str.replace(target, "GFG");

        System.out.println(str);
    }
}


Output

Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.replace(String.java:2142)
at GFG.main(GFG.java:12)

String replace() Method - Java Programs

Let's see some coding problems and solve them with the String charAt() method in Java.

1. Replace Substrings in a String Using the replace() Java method

Java
public class WordReplacement {
    public static void main(String[] args) {
        String sentence = "We are learning JavaScript";
        String wordToReplace = "JavaScript";
        String replacementWord = "Java";
      
        System.out.println("Original sentence: " + sentence);

        String replacedSentence = replaceWord(sentence, wordToReplace, replacementWord);
        System.out.println("Replaced sentence: " + replacedSentence);
    }

    // Method to replace all occurrences of a word in a sentence
    private static String replaceWord(String sentence, String wordToReplace, String replacementWord) {
        // Use replaceAll() method to replace all occurrences
        return sentence.replaceAll("\\b" + wordToReplace + "\\b", replacementWord);
    }
}

Output
Original sentence: We are learning JavaScript
Replaced sentence: We are learning Java

2. Replace Spaces with Underscores Using the replace() Java method

Java
public class ReplaceSpacesExample {
    public static void main(String[] args) {
        String sentence = "Geeks for Geeks";
        String replacedSentence = replaceSpaces(sentence);
        System.out.println("Replaced sentence: " + replacedSentence);
    }

    // Method to replace spaces with underscores
    private static String replaceSpaces(String sentence) {
        return sentence.replace(" ", "_");
    }
}

Output
Replaced sentence: Geeks_for_Geeks

References

To know more about more String Methods refer to the article Java String Methods

Whether you are a beginner starting Java programming or an experienced looking to brush up on your Java skills, this tutorial will provide you with a deep understanding of the replace function and its uses in Java.

The charAt method in Java is a fundamental function for string manipulation. With this guide, you can easily access the characters of a string using the replace function.

Comment

Explore

    Basics
    • Introduction3 min read
    • Variables2 min read
    • Data Types7 min read
    • Operators7 min read
    • Decision Making5 min read
    • Methods7 min read
    • Arrays7 min read
    • Strings5 min read
    OOP & Interface
    • Introduction6 min read
    • Constructors6 min read
    • Encapsulation3 min read
    • Inheritance8 min read
    • Polymorphism5 min read
    • Abstraction5 min read
    • Interfaces8 min read
    Collections
    • Collection class9 min read
    • Collection Interface5 min read
    • List Interface8 min read
    • Set Interface5 min read
    • Queue Interface5 min read
    • Map Interface in Java6 min read
    • Iterator4 min read
    Advance Java Concepts
    • Exception handling6 min read
    • Java Multithreading Tutorial3 min read
    • Synchronization in Java9 min read
    • File handling6 min read
    • Method References3 min read
    • Java 8 Stream Tutorial7 min read
    • Memory Management4 min read
    • Garbage Collection in Java6 min read
    • Networking6 min read
    • JDBC5 min read
    Practice Java
    • Interview Questions15+ min read
    • Programs6 min read
    • Practice Problems5 min read
    • Quiz1 min read
    • Project Ideas15+ min read
    Courses
    • Java Backend Course2 min read
    • Placement 360 Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.