Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
Now Reading
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
A char array in Java internally supports objects known as strings. A string is a type of exceptional array. Arrays are unchangeable, and strings share this feature. Strings can also accommodate characters like arrays do. You can execute various operations on strings, like compare(), split(), replace(), equals(), etc.
This tutorial focuses on the Java string.replace() method, where a new one can replace every occurrence of the old character. This method returns a string to replace each old character with a new char or CharSequence.
Since the launch of JDK 1.5, a new operation has been introduced in Java that allows you to replace an entire sequence of char values.
The replace() method has a specific feature where a null regular expression does not get accepted, this scenario is known as the NullPointerException.
Java replace regex allows you to replace characters with a regular expression. The Java replace() method has several other functionalities, such as:
The replace() method in Java has two different overloads:
Example Syntax:
String originalString = "Hello!";
String replacedString = originalString.replace('o', 'e');
System.out.println(replacedString); // Output: Helle!
In this example, the replace('o', 'e') call replaces all occurrences of the character 'o' with the character 'e' in the original string "Hello!", resulting in the replaced string "Helle!".
Example Syntax:
String originalString = "Hello!";
String replacedString = originalString.replace("Hello", "Hi");
System.out.println(replacedString); // Output: Hi!
In this example, the replace("Hello", "Hi") call replaces all occurrences of the substring "Hello" with the substring "Hi" in the original string "Hello!", resulting in the replaced string "Hi!".
The return value of the replace() method is a new string object that represents the original string with the modifications or replacements made. It does not modify the original string itself because strings in Java are immutable. Instead, the replace() method creates and returns a new string that reflects the modifications.
public class upGrad {
public static void main(String[] args) {
String originalString = "upGras";
String replacedString = originalString.replace('s', 'd');
System.out.println(originalString); // Output: upGras
System.out.println(replacedString); // Output: upGrad
}
}
In this example, the replace() method is called on the originalString object. The return value of the method is assigned to the replacedString variable. Notice that the originalString remains unchanged, while the replacedString contains the modified string with the replacements applied.
It's important to store and use the return value of the replace() method if you want to work with the modified string.
Similar to the Java.String.replace() method, this technique replaces the first substring of the string that has a match between the provided regular expression and the given replacement value.
Identical to the Java.String.replace() operation, this method also returns a resulting string.
public class upGrad {
public static void main(String[] args) {
// Example 1: Replacing a single character
String originalString1 = "upGrad";
String replacedString1 = originalString1.replace('u', 'U');
System.out.println("Example 1:");
System.out.println("Original string: " + originalString1);
System.out.println("Replaced string: " + replacedString1);
System.out.println();
// Example 2: Replacing a substring
String originalString2 = "upGrad";
String replacedString2 = originalString2.replace("Grad", "Skills");
System.out.println("Example 2:");
System.out.println("Original string: " + originalString2);
System.out.println("Replaced string: " + replacedString2);
System.out.println();
// Example 3: Replacing multiple characters
String originalString3 = "upGrad";
String replacedString3 = originalString3.replace("u", "U").replace("p", "P");
System.out.println("Example 3:");
System.out.println("Original string: " + originalString3);
System.out.println("Replaced string: " + replacedString3);
System.out.println();
// Example 4: Replacing multiple characters using regex
String originalString4 = "upGrad";
String replacedString4 = originalString4.replaceAll("[aeiou]", "*");
System.out.println("Example 4:");
System.out.println("Original string: " + originalString4);
System.out.println("Replaced string: " + replacedString4);
}
}
Output:
The above program demonstrates various examples of using Java's replace() method to replace characters or substrings within a string. Let's go through each example in detail:
In this example, the original string upGrad is assigned to the originalString1 variable. The replace() method is then used to replace the character 'u' with 'U', resulting in the modified string UpGrad. The original and replaced strings are printed using System.out.println().
In this example, the original string upGrad is assigned to the originalString2 variable. The replace() method is used to replace the substring "Grad" with "Skills", resulting in the modified string upSkills. Like the previous example, original and replaced strings are printed using System.out.println().
In this example, the original string upGrad is assigned to the originalString3 variable. Chaining multiple replace() methods is applied to replace the characters 'u' and 'p' with their uppercase counterparts, resulting in the modified string UpGrad. The original and replaced strings are then printed using System.out.println().
In this example, the original string upGrad is assigned to the originalString4 variable. The replaceAll() method is used with a regular expression [aeiou] to match and replace all vowels with an asterisk (*), resulting in the modified string *pGr*d. Finally, the original and replaced strings are printed using System.out.println().
public class upGrad {
public static void main(String[] args) {
// Replacing the first occurrence of a substring
String originalString5 = "upGrad";
String replacedString5 = originalString5.replaceFirst("a", "A");
System.out.println("replaceFirst Example:");
System.out.println("Original string: " + originalString5);
System.out.println("Replaced string: " + replacedString5);
}
}
This program begins by defining a class named upGrad. Inside the main method, a string variable originalString5 is declared and assigned the value "upGrad". This variable represents the original string on which the replacement operation will be performed.
The replaceFirst() method is then used on originalString5 to replace the first occurrence of the substring "a" with the character "A". The resulting replaced string is stored in the variable replacedString5.
Finally, to display the output, the program uses System.out.println() to print the heading "replaceFirst Example:". It then prints the original and replaced strings by concatenating them with appropriate messages.
The replace() method in Java does not throw any exceptions on its own. It is a safe operation that performs string replacement without raising any exceptions. Therefore, we do not need to handle specific exceptions using the replace() method.
However, it is important to note that the replace() method creates a new string with the replaced characters and returns it. The original string remains unchanged. So if we wish to store the result of the replace() operation, we must assign it to a variable or use it in some way.
Here is an example:
In the above example, the replace() method is used to replace the substring "World" with "upGrad". The original string remains unchanged, and the replaced string is stored in the replacedString variable.
Code:
public class upGrad {
public static void main(String[] args) {
String originalString = "Hello, World!";
String replacedString = originalString.replace("World", "upGrad");
System.out.println("Original string: " + originalString);
System.out.println("Replaced string: " + replacedString);
}
}
There are three methods of replacing a character in String Class Java, namely:
This tutorial discussed changing characters in Java using the replace() method. You can improve your knowledge of different Java concepts by checking out similar tutorials. If you are keenly interested in joining an educational journey on Java, you can go through the courses available on upGrad that will assist you in refining your Java skills.
1. What is the Difference between Replace() and ReplaceAll()?
The replaceAll() function replaces all the instances of a given substring's occurrence with any desired value. On the other hand, replace() is applicable for replacing a selective number of characters with a new value. The replace() function can only replace a specific quantity or 'n' occurrences of a substring, while replaceAll() changes every occurrence of the characters.
2. How to replace an object in Java?
You can directly replace an object using the replace() method by creating an object that belongs to the string class. The replace() method uses the original string object as an input parameter, followed by returning the new string object. This is the best technique to replace string in Java.
3. How do you remove a letter from a string in Java?
The String class doesn't allow the remove() method to remove letters from a string in Java. You can instead use any variation of the replace() method and the substring() method to remove characters from strings. Knowledge of this method can help work on Java string replace at index with a specified parameter.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...