Menu
Topics Index
...
`


Strings > Modifying a String >
Siva Nookala - 06 Oct 2016
The replace() is used to replace a character or a sequence of characters of an invoking string with a desired character or set of characters .

The replace has two forms:
String replace(char original, char replacement)

This form is used to replace a character with a desired character in the invoking string. Here original specifies the character to be replaced, replacement specifies the character that replaces original.

The other form of replace is:
String replace(CharSequence original, CharSequence replacement)

This form is used to replace a charactersequence with a desired charactersequence in the invoking string. Here also original specifies the character sequence to be replaced, replacement specifies the character sequence that replaces original.

The following program demonstrates replace:
replace
class ReplaceDemo
{
    public static void main(String arg[])
    {
        String sentence = "Moon is bright";
        System.out.println(sentence); // LINE A
        String sentence2 = sentence.replace('M', 'N');
        System.out.println(sentence2); // LINE B
        sentence = sentence + " Moon";
        System.out.println(sentence); // LINE C
        String sentence3 = sentence.replace("Moon", "Sun");
        System.out.println(sentence3); // LINE D    
    }
}
OUTPUT

Moon is bright
Noon is bright
Moon is bright Moon
Sun is bright Sun

DESCRIPTION

At LINE A Moon is bright is the display of the String object sentence. Then sentence.replace('M','N') will replace all occurences of 'M' with 'N' resulting in Noon is bright at LINE B. Then we are concating the sentence with " Moon" and displaying it at LINE C Moon is bright Moon. Then sentence.replace("Moon","Sun") will replace all the occurences of the String Moon with Sun resulting Sun is bright Sun at LINE D.

THINGS TO TRY
  • Try with the below shown code.
    String sentence = "Learn Java";
    String s = sentence.replace("LEARN", "Do");
    System.out.println(s);
    The output should be Lean Java, since replace is case-sensitive.
  • Try with the below shown code.
    String sentence = "Merit Campus online Java tool.";
    String s = sentence.replace("Java", "Java learning");
    System.out.println(s);
    The output should be Merit Campus online Java learning tool. Since Java is replaced with Java learning.

Dependent Topics : Java substring  Java StringBuffer replace() Method With Example 

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App