

{"id":126068,"date":"2024-08-17T18:00:11","date_gmt":"2024-08-17T12:30:11","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=126068"},"modified":"2024-08-17T18:36:54","modified_gmt":"2024-08-17T13:06:54","slug":"java-string-intern-method","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/","title":{"rendered":"Java String intern() Method with Examples"},"content":{"rendered":"<p>The intern() method in Java is a powerful tool for optimizing memory usage and improving the performance of Java applications. Java, a language widely used for its robust string handling, stores string objects in a unique memory area called the String Constant Pool.<\/p>\n<p>When a string is created in Java, it&#8217;s first checked in this pool. If a matching string exists, the existing reference is returned, saving memory and processing resources. If not, a new entry is added to the pool, ensuring only one unique copy of a string resides in memory. This mechanism is the cornerstone of Java&#8217;s memory management strategy, and intern() is the key to unlocking these benefits.<\/p>\n<p>intern() not only conserves memory but also streamlines Java applications. When working with strings, especially during intensive operations like parsing large data, the creation of new string objects can be resource-intensive.<\/p>\n<p>intern() allows developers to alleviate this overhead by reusing existing strings from the String Constant Pool. This results in efficient memory utilization, reduces the need for frequent garbage collection, and ultimately enhances the performance of Java applications.<\/p>\n<p>In this article, we will explore the inner workings of the intern() method, examine its practical applications, and learn how to leverage it to optimize Java programs.<\/p>\n<h2>Method Signature<\/h2>\n<p>The intern() method is a public instance method defined in the String class. It has the following method signature:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public String intern()<\/pre>\n<p>The intern() method returns a String, which is the canonical representation of the string value.<\/p>\n<h3>Need and Working of String.intern()<\/h3>\n<p>By default, String objects in Java are stored in the Heap memory.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">String s1 = \"Hello\"; \r\nString s2 = \"Hello\";<\/pre>\n<p>Here, s1 and s2 refer to two different objects in the Heap. Strings are immutable in Java.<\/p>\n<p>However, the String pool stores a single copy of the String. The intern() method checks if the String already exists in the pool:<\/p>\n<ul>\n<li>If yes, it returns the reference to the pooled String object.<\/li>\n<li>If not, it adds the String to the pool and then returns the reference.<\/li>\n<\/ul>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">String s1 = new String(\"Hello\");\r\nString s2 = s1.intern();<\/pre>\n<p>Here, s2 will refer to the same String object as s1 in the String pool.<\/p>\n<h3>Java String intern() Method Examples<\/h3>\n<h4>Example 1<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class InternExample {\r\n\r\n  public static void main(String[] args) {\r\n    String s1 = new String(\"Hello\");\r\n    String s2 = s1.intern();\r\n\r\n    System.out.println(s1 == s2); \/\/false\r\n\r\n    String s3 = \"Hello\";\r\n    String s4 = \"Hello\"; \r\n\r\n    System.out.println(s3 == s4); \/\/true\r\n  }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nfalse<br \/>\ntrue<\/p>\n<p>Here, s1 and s2 refer to different objects, as s1 was created using a new keyword.<\/p>\n<p>Meanwhile, s3 and s4 refer to the same string object from the pool.<\/p>\n<h4>Example 2<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class InternExample2 {\r\n\r\n  public static void main(String[] args) {\r\n    String s1 = new String(\"Hello\");\r\n    String s2 = \"Hello\";\r\n    s1.intern();\r\n\r\n    System.out.println(s1 == s2); \/\/false\r\n  }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nfalse<\/p>\n<p>Here, even after interning s1, it refers to a different object than s2. Because s1 was already created explicitly earlier.<\/p>\n<h3>Key Points<\/h3>\n<ul>\n<li>String literals like &#8220;Hello&#8221; are automatically interned.<\/li>\n<li>The new keyword always creates a new object.<\/li>\n<li>Calling intern() on an existing String does not replace the original String.<\/li>\n<\/ul>\n<p>So, in most cases, explicitly calling intern() is unnecessary since string literals are automatically interned.<\/p>\n<h3>Conclusion<\/h3>\n<p>In conclusion, Java&#8217;s intern() method optimizes memory and performance by reusing existing String objects from the String Constant Pool. It returns the canonical representation of a string, reducing the need to create new objects. While useful, it&#8217;s important to note that string literals are automatically interned, and calling intern() on them is usually unnecessary. Careful consideration of when to use this method can help strike a balance between memory efficiency and code simplicity, ultimately improving application performance.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The intern() method in Java is a powerful tool for optimizing memory usage and improving the performance of Java applications. Java, a language widely used for its robust string handling, stores string objects in&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":126080,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[31197,7345,31196,31192,31194,31078,8152,31195,31193],"class_list":["post-126068","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-intern-method-in-java","tag-java","tag-java-intern-method","tag-java-string-intern-method","tag-java-string-intern-method-with-examples","tag-java-tutorials","tag-learn-java","tag-string-intern-method","tag-string-intern-method-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java String intern() Method with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"Java&#039;s intern() method optimizes memory and performance by reusing existing String objects from the String Constant Pool.\" \/>\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-intern-method\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java String intern() Method with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Java&#039;s intern() method optimizes memory and performance by reusing existing String objects from the String Constant Pool.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-string-intern-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-08-17T12:30:11+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-08-17T13:06:54+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-intern.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 intern() Method with Examples - DataFlair","description":"Java's intern() method optimizes memory and performance by reusing existing String objects from the String Constant Pool.","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-intern-method\/","og_locale":"en_US","og_type":"article","og_title":"Java String intern() Method with Examples - DataFlair","og_description":"Java's intern() method optimizes memory and performance by reusing existing String objects from the String Constant Pool.","og_url":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-08-17T12:30:11+00:00","article_modified_time":"2024-08-17T13:06:54+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-intern.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-intern-method\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"Java String intern() Method with Examples","datePublished":"2024-08-17T12:30:11+00:00","dateModified":"2024-08-17T13:06:54+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/"},"wordCount":537,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-intern.webp","keywords":["intern() method in java","Java","java intern() method","java string intern() method","java string intern() method with examples","java tutorials","Learn Java","string intern() method","string intern() method in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-string-intern-method\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/","url":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/","name":"Java String intern() Method with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-intern.webp","datePublished":"2024-08-17T12:30:11+00:00","dateModified":"2024-08-17T13:06:54+00:00","description":"Java's intern() method optimizes memory and performance by reusing existing String objects from the String Constant Pool.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-string-intern-method\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-string-intern-method\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-intern.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-intern.webp","width":1200,"height":628,"caption":"java string intern()"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-string-intern-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 intern() 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\/126068","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=126068"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126068\/revisions"}],"predecessor-version":[{"id":143203,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126068\/revisions\/143203"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/126080"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=126068"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=126068"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=126068"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}