Function Description
Java String class replace() method is used to replace all occurrences of the old character or sequence of characters respectively with new character or sequence of characters in the string.
- If the specified old character or sequence of characters is not found in the sting, It will return the same string.
- If the specified old character or sequence of characters finds in the sting, It will return a string resulting from replacing all occurrences of character(s).
- If the specified old character or sequence of characters is null, It will throw NullPointerException.
- If the specified new character or sequence of characters is null, It will throw NullPointerException.
Replace is an overloaded method in String class.
- One method is to replace the character
- Another method is to replace the sequence of characters
For Example, String in which you want to replace the character/ sequence of characters is “lkarn rkplack method”, see what replace() method will return.
- “lkarn rkplack method”.replace(“g”,”e”) will return “lkarn rkplack method”
- “lkarn rkplack method”.replace(“k”,”e”) will return “learn replace method”
- “lkarn rkplack method”.replace(null,”e”) will throw NullPointer Exception
- “lkarn rkplack method”.replace(“k”, null) will throw NullPointer Exception
Method Signature
Method to replace character
public String replace(char oldChar, char newChar)
Method to replace the sequence of characters
public String replace(CharSequence target, CharSequence replacement)
Parameters
oldChar : A character of the string to be replaced in the string
newChar: New character to replace the old character in the string
target: The sequence of characters to be replaced in the string
replacement: Sequence of characters to replace the old sequence of characters in the string
Return Type
Replaced string after replacing old character(s) with the specified new character(s)
Exception
Throws NullPointerException if either of the specified parameters (oldChar, newChar, target or replacement ) is null
Example of Java String Class replace() Method
- Example of Java String Class replace() method to replace character
package com.java.test; public class ExampleStringReplace { private void replaceCharacter(String str) { // replace character 4 with 6 String relacedString = str.replace('4', '6'); System.out.println("After replacing character 4 with 6 :" + relacedString); } public static void main(String[] args) { String str = "1234 1245 1256"; System.out.println("Input String : " + str); System.out.println(""); ExampleStringReplace exampleStringReplace = new ExampleStringReplace(); exampleStringReplace.replaceCharacter(str); } } Output: Input String : 1234 1245 1256 After replacing character 4 with 6 :1236 1265 1256
2. Example of Java Sting Class replace() method to replace sequence of characters
package com.java.test; public class ExampleStringReplace { private void replaceString(String str) { // replace charactersequence 12 with 67 in the given string String relacedString = str.replace("12", "67"); System.out.println("After replace 12 with 67 : " + relacedString); } public static void main(String[] args) { String str = "1234 1245 1256"; System.out.println("Input String : " + str); System.out.println(""); ExampleStringReplace exampleStringReplace = new ExampleStringReplace(); exampleStringReplace.replaceString(str); } } Output: Input String : 1234 1245 1256 After replace 12 with 67 : 6734 6745 6756
3. Example when NullPointerException is thrown
package com.java.test; public class ExampleStringReplace { private void replaceString(String str) { // replace charactersequence 12 with 67 in the given string String relacedString = str.replace(null, "67"); System.out.println("After replace 12 with 67 : " + relacedString); } public static void main(String[] args) { String str = "1234 1245 1256"; System.out.println("Input String : " + str); System.out.println(""); ExampleStringReplace exampleStringReplace = new ExampleStringReplace(); exampleStringReplace.replaceString(str); } } Output: Input String : 1234 1245 1256 Exception in thread "main" java.lang.NullPointerException at java.lang.String.replace(String.java:2239) at com.java.test.ExampleStringReplace.replaceString(ExampleStringReplace.java:8) at com.java.test.ExampleStringReplace.main(ExampleStringReplace.java:17)
Other Methods of String Class
Sequence | Method | Description |
1 | char charAt(int index) | This method is used to return the character of the string at specified index. First character is at index 0 while last is at string length-1 . StringIndexOutOfBounds Exception is thrown if valid index value is not passed. |
2 | int length() | Returns the number of characters count in a string. |
3 | static String format(String format, Object… args) | Return the formatted String. It is a static method and formats the string as per passing format and argument(s). |
4 | static String format(Locale l, String format, Object… args) | Return the formatted String. It is a static method and formats the string as per passing format and argument(s) and locale. |
5 | String substring(int beginIndex) | Returns substring from the given index position to the end index of the string. |
6 | String substring(int beginIndex, int endIndex) | Returns substring from the specified begin index to the specified end index. |
7 | boolean contains(CharSequence s) | Returns boolean value(true/false). It searches the given sequence of characters within the string and returns true/false accordingly. Characters will be case sensitive while searching in string. |
8 | static String join(CharSequence delimiter, CharSequence… elements) | Returns joined string. This method joins each passing String using the specified delimiter. It is a static method. |
9 | static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) | Returns the joined string. This method joins each passing string object of an iterate object using the specified delimiter and returns the concatenated string. It is a static method. |
10 | boolean equals(Object another) | Returns boolean value(true/false). It checks the equality of string with the passing object. |
11 | boolean isEmpty() | Returns boolean value(true/false). It returns true if the string is empty otherwise returns false. |
12 | String concat(String str) | Returns the concatenating string. It concatenates the passing string at the end of the string. |
13 | String replaceAll(String regex, String replacement) | Returns the replaced string. It replaces all occurrences of the sequence of characters with the given replacement string that are matching with the given regular expression. |
14 | String replaceFirst(String regex, String replacement) | Returns the replaced string. It replaces the first matching sequence of characters with the replacement string that matches with the given regular expression. |
15 | static boolean equalsIgnoreCase(String another) | Returns the boolean (true/false) value. It compares the passing string with string by ignoring the case. It compares the content irrespective of lowercase or uppercase of the character(s). |
16 | String[] split(String regex) | Returns the array of strings resulting from splitting of the string around matches of the given regular expression. String is breaked into strings from all the matching regular expressions. |
17 | String[] split(String regex, int limit) | Returns the array of strings resulting from splitting of the string around matches of the given regular expression. It breaks the string from all the matching regular expression upto the given limit. |
18 | String intern() | Returns an interned string. This method helps to compare two objects using == operator and checks in a string constant pool. it is faster for comparison. |
19 | int indexOf(int ch) | Returns the index value of first occurrence of the specified character within the string |
20 | int indexOf(int ch, int fromIndex) | Returns the index value of first occurrence of the specified character from the substring starting from specified index |
21 | int indexOf(String substring) | Returns the index value of first occurrence of the specified substring within the string. |
22 | int indexOf(String substring, int fromIndex) | Returns the index value of the first occurrence of the specified string within the substring starting from specified index to end of the string index. |
23 | int lastIndexOf(int ch) | Returns the index value of last occurrence of the specified character |
24 | int lastIndexOf (int ch, int fromIndex) | Returns the index value of last occurrence of the specified character, search starts at given fromIndex. |
25 | int lastIndexOf (String str) | Returns the index value of last occurrence of the specified string. |
26 | int lastIndexOf (String str, int fromIndex | Returns the index value of last occurrence of the specified string, searches start from given fromIndex |
27 | String toLowerCase() | Returns all the characters of the string in lowercase . |
28 | String toLowerCase(Locale l) | Returns all the characters of the string in lowercase using specified locale. |
29 | String toUpperCase() | Returns all the characters of the string in uppercase. |
30 | String toUpperCase(Locale l) | Returns all the characters of the string in uppercase using specified locale. |
31 | String trim() | Returns the string after removing the white space from the beginning and end of the string. |
32 | static String valueOf(int value) | Return the converted string. It converts the objects and all primitive types of values into string. It is a static method. |
In this article, we learned all about the replace() method of Java String class with examples. Apart from replace() method we got an idea about other String methods too. We will come up with more articles explaining other String methods with examples. For more details please click on the respective methods link.