{"id":89398,"date":"2025-03-11T18:00:55","date_gmt":"2025-03-11T12:30:55","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=89398"},"modified":"2025-03-12T12:38:24","modified_gmt":"2025-03-12T07:08:24","slug":"java-string-replace-method","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/","title":{"rendered":"Java String replace() Method"},"content":{"rendered":"<p>The replace() method searches for a given character in a string and returns a new string where the given characters are replaced. In this method, a new string is returned when new ones replace occurrences of old characters.<\/p>\n<p><strong>What are the common replace() methods of the String class in Java?<\/strong><\/p>\n<p>The String class provides four different kinds of replace() methods in Java. Each method solves a specific use case.<\/p>\n<p><strong> Their names are given below:<\/strong><\/p>\n<p class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">replace (char, char)<br \/>\nreplace(string, string)<br \/>\nreplace all(string, string)<br \/>\nreplaceFirst(string, string)<\/p>\n<h2>Java String replacement() method<\/h2>\n<p>The Java String replace() method replaces the specified character with the given character, both passed as parameters. This method is suitable for replacing any character in a string with another character of your choice.<\/p>\n<p><strong>Method headers<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public String replace(oldCharacter, character newCharacter).<\/pre>\n<h3>Method parameters:<\/h3>\n<p><strong>The method takes two parameters or arguments of type &#8220;char&#8221;.<\/strong><\/p>\n<ul>\n<li>char oldCharacter contains the character to be replaced.<\/li>\n<li>char newCharacter contains the character that will be used instead of the old character.<\/li>\n<\/ul>\n<p><strong>Return type:<\/strong><\/p>\n<p>The String replace method returns the updated string after replacing the required character.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<p><strong>Let&#8217;s look at various simple examples to understand how this method works.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class Driver {\r\npublic static void main(String[] args) {\r\nSystem.out.println(\"Original sentence: \\t\\t\\t\" + my string);\r\nchar oldCharacter = 'a'; \r\nchar newCharacter = 'A'; \r\n            String updatedString = myString.replace(oldCharacter, NewCharacter);\r\nsystem.out.println(\"After replacing '\" + oldCharacter + \"' with '\" \r\nnewCharacter + \"': \\t\\t\" + updatedString);\r\nString oldString = \"apple\";\r\nString newString = \"orange\";\r\n            String updatedString1 = myString.replace(oldString, newString);\r\n            System.out.println(\"Replacing '\" + oldString + \"' with '\" +\r\n        newString + \"': \\t\" + updatedString1 + \"\\n\");\r\n}\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>After replacing all o with T:<\/strong> WelcTme tT techvidvan<\/p>\n<h3>1. NullPointerException<\/h3>\n<p>The replace() method does not accept the regular expression null, it throws a NullPointerException.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import java.io.*;\r\nclass techvidvan {\r\npublic static void main(String[] args)\r\n{\r\nString str = \"techvidvan\";\r\nint size = str.length();\r\nSystem.out.println(str);\r\nString target = null;\r\nstr = str.replace(target, \"GFG\");\r\nSystem.out.println(str)Exception in thread \"main\" java.lang.NullPointerException\r\n    at java.base\/java.lang.String.replace(String.java:2142)\r\n    at techvidvan.main(techvidvan.java:12);\r\n}\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nExException in thread &#8220;main&#8221; java.lang.NullPointerException<br \/>\nat java.base\/java.lang.String.replace<br \/>\nat GFG.main<\/p>\n<p><strong>Example for Java String replace():<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class techvidvan {\r\npublic static void main(String args[])\r\n{\r\nString Str = new String(\"Welcome to techvidvan\");\r\nSystem.out.print(\"Original string: \");\r\nSystem.out.println(Str);\r\nSystem.out.print(\r\nSystem.out.println(\r\nStr.replaceFirst(\"techvidvan\", \"ASTHA\"));\r\n}\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>Original String:<\/strong> Welcome to techvidvan<br \/>\n<strong>After replacing 1st occurrence of regex with replace_str :<\/strong> Welcome to ASTHAfortechvidvan.<\/p>\n<h4>Replace the substring:<\/h4>\n<p>The chef informed us that he wanted to update the name of the ham sandwich to the Ham Deluxe to reflect the addition of new ingredients.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Aclass Replace techvidvan {\r\npublic static void main(String[] args) {\r\nString ham_entry = \"Ham: $3.00.\";\r\nString new_ham_entry = ham_entry.replace(\"Ham\", \"Ham Deluxe\");\r\nSystem.out.println(new_ham_entry);\r\n}\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>Ham Deluxe:<\/strong> $3.00.<\/p>\n<p>Let&#8217;s break down our code. First, we define a class called ReplaceSandwiches that holds the code for our program. We then declare a variable called ham_entry that stores the name of the ham sandwich and its price.<\/p>\n<p>To replace the word &#8220;ham&#8221; in a ham_entry string with Ham Deluxe, we use Replace() method. The new_ham_entry variable is assigned the result of the replace() method. In conclusion, the contents of new_ham_ entry are printed in our program into the console. We now have an updated entry for the ham sandwich.<\/p>\n<h4>Replace character<\/h4>\n<p>The replace() method can also replace a single character with another character. Instead of appearing as Ham, we wrote Hom. We know that there is only one o in our string and we want to replace it with a.<\/p>\n<p><strong>We could use the following code to fix our error:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class techvidvan {\r\npublic static void main(String[] args) {\r\nString ham_entry = \"Ham Deluxe: $3.00.\";\r\nString new_ham_entry = ham_entry.replace(\"o\", \"a\");\r\nSystem.out.println(new_ham_entry);\r\n}\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>Original String:<\/strong> Welcome to techvidvan<br \/>\n<strong>After replacing 1st occurrence of regex with replace_str :<\/strong> Welcome to ASTHAfortechvidvan.<\/p>\n<p>Our program works just like our previous example, but this time, we&#8217;re replacing one character rather than a series of characters. In this case, we&#8217;ve replaced the o with the o.<\/p>\n<p>Replace multiple instances. A new character or substring replaces each instance of a character or substring by the replace() method. For example, given that our string contains just one instance of the substring and character, we&#8217;ve substituted it with a single instance. But if there were several instances of a character or substring, all these would be substituted for them. Suppose we have a string that stores the text that will appear on a banner telling customers that the restaurant.<\/p>\n<p><strong>Program:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class techvidvan {\r\npublic static void main(String[] args) {\r\nString new_banner = ham_entry.replace(\"MENU\", \"Sal's Kitchen\");\r\nSystem.out.println(new_banner);\r\n}\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nSal\u2019s Kitchen<br \/>\nCome see the new menu!<br \/>\nSal\u2019s Kitchen.<\/p>\n<p>Our code works just like our previous examples. However, since our initial string contains the word MENU twice, the replace() method replaces both instances. It&#8217;s worth noting that the lowercase word menu also appears in our string, but since replace() is case sensitive, it&#8217;s not replaced.<\/p>\n<h3>Advantages<\/h3>\n<ul>\n<li><strong>The ease of use:<\/strong> Using and manipulating the strings is simple. It is also possible to concatenate, slice and reverse them. It also comes with easy and intuitive syntax, allowing programmers at all levels of expertise to use it. Compatibility: Strings are commonly used in programming, making them a common data type. It means that strings can be easily exchanged among different systems and platforms, which gives them high reliability and efficiency in communicating and sharing data.<\/li>\n<li><strong>Compatibility:<\/strong> Strings are the most common data type because they can be used in various programming languages. This makes transferring them from one system or platform to another easy, making them reliable and effective for data exchange and sharing.<\/li>\n<\/ul>\n<h3>Disadvantages<\/h3>\n<ul>\n<li><strong>Mutability:<\/strong> In many programming languages, strings are immutable and cannot be changed after creation. Working with large or complex strings that require frequent changes may be disadvantageous because they can lead to inefficiencies and memory bottlenecks.<\/li>\n<li><strong>Memory consumption:<\/strong> Strings may consume too much memory when working on big strings or a lot of strings. This may be a problem in environments with limited memory, e.g., embedded systems or portable devices.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>The replace() method is used in Java to replace each instance of a particular character or substring with another character or substring. This tutorial discussed how to use replace() to replace single characters, substrings, and multiple instances of a character or substring. We&#8217;ve also explored some detailed examples of the replace() method in action.<\/p>\n<p>You are now equipped with the information you need to use the replace() function in Java to replace the contents of a string like a pro!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The replace() method searches for a given character in a string and returns a new string where the given characters are replaced. In this method, a new string is returned when new ones replace&#46;&#46;&#46;<\/p>\n","protected":false},"author":6,"featured_media":447358,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[257,5700,299,263,250,260,261],"class_list":["post-89398","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java-string-replace","tag-java-string-replace-method","tag-java-tutorial","tag-java-tutorial-for-beginners","tag-learn-java","tag-string-replace","tag-string-replace-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java String replace() Method - TechVidvan<\/title>\n<meta name=\"description\" content=\"In Java, the replace() method replaces each instance of a particular character or substring with another character or substring.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java String replace() Method - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"In Java, the replace() method replaces each instance of a particular character or substring with another character or substring.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2025-03-11T12:30:55+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-03-12T07:08:24+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/04\/java-String-replace.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java String replace() Method - TechVidvan","description":"In Java, the replace() method replaces each instance of a particular character or substring with another character or substring.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/","og_locale":"en_US","og_type":"article","og_title":"Java String replace() Method - TechVidvan","og_description":"In Java, the replace() method replaces each instance of a particular character or substring with another character or substring.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2025-03-11T12:30:55+00:00","article_modified_time":"2025-03-12T07:08:24+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/04\/java-String-replace.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/dde481bb412350cde1ed6e389bc0deaf"},"headline":"Java String replace() Method","datePublished":"2025-03-11T12:30:55+00:00","dateModified":"2025-03-12T07:08:24+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/"},"wordCount":902,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/04\/java-String-replace.webp","keywords":["java string replace()","java string replace() method","Java Tutorial","java tutorial for beginners","Learn Java","string replace()","string replace() in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/","url":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/","name":"Java String replace() Method - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/04\/java-String-replace.webp","datePublished":"2025-03-11T12:30:55+00:00","dateModified":"2025-03-12T07:08:24+00:00","description":"In Java, the replace() method replaces each instance of a particular character or substring with another character or substring.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/04\/java-String-replace.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/04\/java-String-replace.webp","width":1200,"height":628,"caption":"java string replace()"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-string-replace-method\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java String replace() Method"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/dde481bb412350cde1ed6e389bc0deaf","name":"TechVidvan Team"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89398","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=89398"}],"version-history":[{"count":4,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89398\/revisions"}],"predecessor-version":[{"id":447811,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89398\/revisions\/447811"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/447358"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=89398"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=89398"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=89398"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}