Difference Between replace() and replaceAll() in JavaThe Java String class provides various methods to manipulate string. The replace() and replaceAll() method are one of them that are used to replace a string with a specified sub string. As the name of both the methods sounds same but their working is different. Let's understand replace(), replaceAll() and replaceFirst() methods and differentiate each one of them one by one. String.replace() MethodThe replace() method is one of the most used string methods for replacing all the occurrences of a character with the given character. The replace() method of JDK 1.5 replaces the char and a sequence of char values. Syntax: These are the following two types of replace() methods in the Java String class. Parameters prevChar: The parameter defines the character of the string to be replace. newChar: The parameter defines the newChar that takes the place of the prevChar. target: The parameter defines the target sequence of characters. replacement: The parameter defines the replacement sequence of characters. Let's take an example to understand how we can use the replace() method in Java programs. ReplaceExample1.java Output: String.replaceAll() MethodThe replaceAll() method is similar to the String.replaceFirst() method. The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: Parameters str: The parameter defines the sub-string that we need to replace in the string. replacement: The parameter defines the replacement string that takes the place of the str. Let's take an example to understand how we can use the replaceAll() method in our programs. ReplaceExample3.java Output: String.replaceFirst() MethodThe replaceFirst() method is another method for replacing the substring. It replaces the sub-string with the given string. The replaceFirst() method replaces only the first occurrence of the sub-string. Syntax: The syntax of the replaceFirst() method is as follows: Parameters Str: The parameter defines the sub-string that we need to replace in the string. Replacement: The parameter defines the replacement string that takes the place of the str. Let's take an example to understand how we can use the replaceFirst() method in our programs. ReplaceExample2.java Output: |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India