Java String Replace
As the name of the method says, with this method, we can replace some specified old characters from the string, with the specified new character. This is like saying – hey… find all the c from the string and change them to g. Well, here, c is the old character, and g is a new character. Remember that all the occurrences of the old character will be replaced by the new character.
Let’s consider an example to understand the same thing –
public class StringMethods {
public static void main(String[] args) {
String str1 = “This food house serves good food”;
System.out.println(str1.replace(‘o’, ‘u’));
}
}
So, in the above program, we are just replacing all the occurrences of the character ‘o’ from the string, with ‘u’. You can try executing the program and observe the output. Remember that this method returns a string, with all the replacements. Have a look at the output –
This fuud huuse serves guud fuud
As you can see, all the occurrences of the old character ‘o’, were replaced by the new character ‘u’.
But one thing is that what if we give such a character that never occurs in the string? Well, in such a situation, there won’t be any error. It would just return the same string. Have a look at the program in which we try to replace all the character ‘b’ from the string. And in fact, there is no ‘b’ in the string –
public class StringMethods {
public static void main(String[] args) {
String str1 = “This food house serves good food”;
System.out.println(str1.replace(‘b’, ‘u’));
}
}
So, if we execute the above program, there is no error saying – hey… there is no ‘b’ in here! What should I do now? It is going to just give the normal string back, without doing any changes.
Well, you may consider that exceptions occur when the program does not know what to do(well… this is not the case here). For example, if you have written an instruction to open some files from some folder. Now one case is that no such file exists there in that folder, from which you are trying to open the file.
Now, the file is not found and the program cannot do anything. Hence, it throws an exception saying something like – hey, I could not find a such file that you told me. I don’t know what to do now, I am just hanging up. We are going to study exceptions in the concept of exception handling. I just wanted to highlight this thing here once for your curiosity.
But this is not the case here. We are just getting the same string as the output in the case if we give such a character for replacement, which never existed in the string.
In the above method, we had just replaced some characters. But what if we need to replace all occurrences of some word, or a set of words? Well, we have another method for doing this.