

{"id":126625,"date":"2024-11-27T18:00:50","date_gmt":"2024-11-27T12:30:50","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=126625"},"modified":"2024-11-27T18:11:06","modified_gmt":"2024-11-27T12:41:06","slug":"java-string-replace-method","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/","title":{"rendered":"Java String replace() Method with Examples"},"content":{"rendered":"<p>Strings in Java are objects backed internally by a char array. They are immutable, just like arrays; their values cannot be changed once initialized. This immutability makes them a fundamental data structure in Java, particularly for storing and manipulating text-based information.<\/p>\n<p>The String class in Java contains several useful methods for manipulating strings. One such method is the replace() method, which can be used to replace characters or substrings in a string with new characters or substrings. This makes it an indispensable tool for text processing and manipulation in Java.<\/p>\n<p>In this article, we&#8217;ll explore the intricacies of the Java String replace() method and how it can be leveraged to streamline string manipulation tasks.<\/p>\n<h2>Java String replace() Method<\/h2>\n<p>The replace() method in the Java String class replaces every occurrence of a character\/substring with a new character\/substring and returns the resulting string.<\/p>\n<p><strong>Syntax<\/strong><\/p>\n<p><strong>The syntaxes for the two variants of replace() method are:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public String replace(char oldChar, char newChar)\r\n\r\npublic String replace(CharSequence target, CharSequence replacement)<\/pre>\n<p><strong>Parameters<\/strong><\/p>\n<p><strong>The parameters for replace() method are:<\/strong><\/p>\n<ul>\n<li><strong>oldChar &#8211;<\/strong> The old char to be replaced<\/li>\n<li><strong>newChar &#8211;<\/strong> The new char to replace oldChar<\/li>\n<li><strong>target &#8211;<\/strong> The target substring to be replaced<\/li>\n<li><strong>replacement &#8211;<\/strong> The replacement substring<\/li>\n<\/ul>\n<p><strong>Return Value<\/strong><\/p>\n<p>The replace() method returns a string resulting from replacing all occurrences of oldChar\/target with newChar\/replacement, respectively.<\/p>\n<h3>Examples of Java String replace()<\/h3>\n<p>Let&#8217;s look at some examples to understand the usage of replace() method.<\/p>\n<p><strong>Example 1:<\/strong> Using replace(char old, char new)<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class StringReplaceExample {\r\n    public static void main(String[] args) {\r\n        String str = \"Hello World\";\r\n        String newStr = str.replace('l', 'w');\r\n        System.out.println(newStr);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nHewwo Word<\/p>\n<p><strong>Example 2:<\/strong> Using replace(String target, String replacement)<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class StringReplaceExample {\r\n    public static void main(String[] args) {\r\n        String str = \"Hello World\";\r\n        String newStr = str.replace(\"World\", \"Universe\");\r\n        System.out.println(newStr);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nHello Universe<\/p>\n<h3>Exceptions with replace() Method<\/h3>\n<p>If we pass a null regular expression to replace(), it results in NullPointerException.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class StringReplaceExample {\r\n    public static void main(String[] args) {\r\n        String str = \"Hello\";\r\n        String regex = null;\r\n\r\n        try {\r\n            str = str.replace(regex, \"Hi\");\r\n            System.out.println(str);\r\n        } catch (NullPointerException e) {\r\n            System.out.println(\"NullPointerException occurred: \" + e.getMessage());\r\n        }\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>NullPointerException occurred:<\/strong> replace(CharSequence target, CharSequence replacement)<\/p>\n<p>This is because replace() expects a valid regular expression and cannot work with a null value.<\/p>\n<h3>Java String replaceFirst()<\/h3>\n<p>Along with replace(), String class also provides replaceFirst() method which replaces only the first occurrence of a substring.<\/p>\n<p><strong>Syntax<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public String replaceFirst(String regex, String replacement)<\/pre>\n<p><strong>Parameters<\/strong><\/p>\n<p>regex &#8211; The regular expression to match<br \/>\nreplacement &#8211; The string to replace the regex<\/p>\n<p><strong>Return Value<\/strong><\/p>\n<p>It returns a string with the first matching regex replaced.<\/p>\n<h3>Example of Java String replaceFirst()<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class StringReplaceExample {\r\n    public static void main(String[] args) {\r\n        String str = \"Hello World\";\r\n        String result = str.replaceFirst(\"l\", \"w\");\r\n        System.out.println(result);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nHewlo World<\/p>\n<h3>Conclusion<\/h3>\n<p>In conclusion, the Java String replace() method is valuable for manipulating strings. It allows you to replace all occurrences of a character or substring with a new character or substring in a string. There are two variants of the method, one for replacing characters and another for replacing substrings. It returns a new string with the replacements, leaving the original string unchanged. However, it&#8217;s important to note that passing a null regular expression to replace() will result in a NullPointerException.<\/p>\n<p>Additionally, Java offers a replaceFirst() method to replace only the first occurrence of a substring in a string, providing flexibility in string manipulation.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Strings in Java are objects backed internally by a char array. They are immutable, just like arrays; their values cannot be changed once initialized. This immutability makes them a fundamental data structure in Java,&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":134334,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[7345,31229,31224,31227,31078,8152,31230,31228,31226,31225],"class_list":["post-126625","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java","tag-java-replace-method","tag-java-string-replace-method","tag-java-string-replace-method-with-examples","tag-java-tutorials","tag-learn-java","tag-replace-method","tag-replace-method-in-java","tag-string-replace-method","tag-string-replace-method-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java String replace() Method with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"Java String replace() method allows you to replace all occurrences of a character or substring with a new character or substring in a string.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/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 with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Java String replace() method allows you to replace all occurrences of a character or substring with a new character or substring in a string.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-27T12:30:50+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-27T12:41:06+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/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=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\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=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java String replace() Method with Examples - DataFlair","description":"Java String replace() method allows you to replace all occurrences of a character or substring with a new character or substring in a string.","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:\/\/data-flair.training\/blogs\/java-string-replace-method\/","og_locale":"en_US","og_type":"article","og_title":"Java String replace() Method with Examples - DataFlair","og_description":"Java String replace() method allows you to replace all occurrences of a character or substring with a new character or substring in a string.","og_url":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-11-27T12:30:50+00:00","article_modified_time":"2024-11-27T12:41:06+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replace.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"Java String replace() Method with Examples","datePublished":"2024-11-27T12:30:50+00:00","dateModified":"2024-11-27T12:41:06+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/"},"wordCount":461,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replace.webp","keywords":["Java","java replace() method","java string replace() method","java string replace() method with examples","java tutorials","Learn Java","replace() method","replace() method in java","string replace() method","string replace() method in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-string-replace-method\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/","url":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/","name":"Java String replace() Method with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replace.webp","datePublished":"2024-11-27T12:30:50+00:00","dateModified":"2024-11-27T12:41:06+00:00","description":"Java String replace() method allows you to replace all occurrences of a character or substring with a new character or substring in a string.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-string-replace-method\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replace.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-replace.webp","width":1200,"height":628,"caption":"java string replace()"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-string-replace-method\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Java Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/java\/"},{"@type":"ListItem","position":3,"name":"Java String replace() Method with Examples"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49","name":"TechVidvan Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","caption":"TechVidvan Team"},"description":"TechVidvan Team provides high-quality content &amp; courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.","url":"https:\/\/data-flair.training\/blogs\/author\/test001\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126625","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/86671"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=126625"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126625\/revisions"}],"predecessor-version":[{"id":143634,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126625\/revisions\/143634"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/134334"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=126625"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=126625"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=126625"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}