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.


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