Menu
Topics Index
...
`

replace - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App