Make Selenium Easy

Java Program 10: Replace All Occurrence Of Sub string In Given String

Hello folks,

In this post, we will learn how to replace a sub string in a given string. Detailed description of problem is given below:

You have an input string and you need to replace sub string from new sub string in given input string.


Input: This bike is my bike.
Action: Replace “bike” from “car.
output: This car is my car.


  1. We will use split method and will split given input string from word which needs to be replaced. Remember, how split works.
  2. After split, add new word at end of all split word except last one.
  3. First verify if last word in input string is equal to string to be replaced. If yes then append new word.



I have put comments wherever it is necessary. If you have any doubt, you can ask me.


Table of Contents

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

2 thoughts on “Java Program 10: Replace All Occurrence Of Sub string In Given String

  1. public class ReplaceAllDemo {
    public static void main(String[] args) {

    Scanner sc = new Scanner(;
    System.out.println(“Enter string:”);
    String inputString = sc.nextLine();
    System.out.println(“Enter word to be replaced from:”);
    String from = sc.nextLine();
    System.out.println(“Enter word to replaced to:”);
    String to = sc.nextLine();
    System.out.println(“Input string: ” + inputString);
    System.out.println(“Word to be replaced from: ” + from);
    System.out.println(“Word to be replaced to: ” + to);

    inputString = inputString.replaceAll(from, to);

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.

Java Program 10: Replace All Occurrence Of Sub string In Given String

by Amod Mahajan time to read: 2 min
%d bloggers like this: