Java Program to replace one specific character with another


Use the replace() method to replace a specific character with another. Let’s say the following is our string and here we are replacing a whitespace with a $ character.

String str1 = "Orange is the new Black!";

Now, use the replace() method to replace a character with $

str1.replace(' ', '$');

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str1 = "Orange is the new Black!";
      System.out.println("String: "+str1);
      String str2 = str1.replace(' ', '$');
      System.out.println("Updated string: "+str2);
   }
}

Output

String: Orange is the new Black!
Updated string: Orange$is$the$new$Black!

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

480 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements