

{"id":123461,"date":"2024-11-13T18:00:48","date_gmt":"2024-11-13T12:30:48","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=123461"},"modified":"2024-11-13T18:11:28","modified_gmt":"2024-11-13T12:41:28","slug":"java-stringbuilder-class","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/","title":{"rendered":"StringBuilder Class in Java with Examples"},"content":{"rendered":"<p>The StringBuilder class in Java enables the creation of adjustable sequences of characters. Unlike immutable Strings, StringBuilder allows modifying the character content after creation. This makes StringBuilder worthwhile when you frequently change the string value without creating new String objects.<\/p>\n<p>StringBuilder is similar in some ways to StringBuffer &#8211; both allow mutable strings. However, a key difference is that StringBuilder is non-synchronized for use by a single thread, while StringBuffer is synchronized and thread-safe.<\/p>\n<p>StringBuilder&#8217;s advantage is that it performs better in single-threaded contexts since it avoids the overhead of synchronization. However, it cannot be safely used by multiple threads concurrently, so StringBuffer is more suitable.<\/p>\n<h2>Constructors in Java StringBuilder Class<\/h2>\n<ul>\n<li><strong>StringBuilder() &#8211;<\/strong> Creates an empty string builder with default initial capacity.<\/li>\n<li><strong>StringBuilder(int capacity) &#8211;<\/strong> Creates an empty string builder with a specified initial capacity.<\/li>\n<li><b>StringBuilder(CharSequence seq) &#8211; <\/b>Creates string builder containing the same characters as a passed sequence.<\/li>\n<li><strong>StringBuilder(String str) &#8211;<\/strong> Creates string builder initialized with same chars as passed string.<\/li>\n<\/ul>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class Main {\r\n  public static void main(String[] args) {\r\n    StringBuilder sb1 = new StringBuilder();\r\n    StringBuilder sb2 = new StringBuilder(50); \r\n    CharSequence cs = \"Hello\";\r\n    StringBuilder sb3 = new StringBuilder(cs);\r\n    String s = \"World\";\r\n    StringBuilder sb4 = new StringBuilder(s);\r\n    \r\n    System.out.println(sb1);\r\n    System.out.println(sb2);\r\n    System.out.println(sb3);\r\n    System.out.println(sb4);\r\n  }\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Hello<br \/>\nWorld<\/p>\n<h3>Methods in Java StringBuilder<\/h3>\n<p><strong>StringBuilder provides a variety of methods to modify a sequence of characters:<\/strong><\/p>\n<table>\n<tbody>\n<tr>\n<td><b>Method<\/b><\/td>\n<td><b>Description<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">append(X x)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Appends string representation of x to sequence<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">appendCodePoint(int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Appends Unicode code point<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">capacity()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns current capacity<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">charAt(int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns char at index<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">chars()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns stream of chars<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">codePointAt(int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns code point at index<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">codePointBefore(int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns code point before index<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">codePointCount(int, int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns count in text range<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">codePoints()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns stream of code points<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">delete(int, int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Deletes characters in range<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">deleteCharAt(int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Deletes char at index<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">ensureCapacity(int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Ensures minimum capacity<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">getChars(int, int, char[], int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Copies chars into array<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">indexOf()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns index of substring\/char<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">insert(int, boolean)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Inserts value at offset<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">insert(int, String)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Inserts string at offset<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">lastIndexOf()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns last index of substring\/char<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">length()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns length<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">offsetByCodePoints(int, int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns offset index<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">replace(int, int, String)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Replaces substring<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">reverse()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Reverses sequence<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">setCharAt(int, char)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Sets char at index<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">setLength(int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Sets length<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">subSequence(int, int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns subsequence<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">substring(int)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Returns substring<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">toString()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Converts to String<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">trimToSize()<\/span><\/td>\n<td><span style=\"font-weight: 400\">Trims capacity to length<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Example:<\/strong><\/p>\n<p>The provided example showcases a few of Java&#8217;s most commonly used string manipulation methods, demonstrating their practical applications in real-world scenarios.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class StringMethodsDemo {\r\n    public static void main(String[] args) {\r\n        String originalString = \"Hello, World!\";\r\n\r\n        \/\/ Using the charAt method to retrieve a character at a specific index\r\n        char charAtIndex3 = originalString.charAt(3);\r\n        System.out.println(\"Character at index 3: \" + charAtIndex3);\r\n\r\n        \/\/ Using the length method to get the length of the string\r\n        int stringLength = originalString.length();\r\n        System.out.println(\"String length: \" + stringLength);\r\n\r\n        \/\/ Using the substring method to extract a substring\r\n        String substring = originalString.substring(7);\r\n        System.out.println(\"Substring from index 7: \" + substring);\r\n\r\n        \/\/ Using the replace method to replace a portion of the string\r\n        String replacedString = originalString.replace(\"World\", \"Java\");\r\n        System.out.println(\"Replaced String: \" + replacedString);\r\n\r\n        \/\/ Using the toString method to convert the string to its string representation\r\n        String stringRepresentation = originalString.toString();\r\n        System.out.println(\"String representation: \" + stringRepresentation);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>Character at index 3:<\/strong> 1<br \/>\n<strong>String length:<\/strong> 13<br \/>\n<strong>Substring from index 7:<\/strong> World!<br \/>\n<strong>Replaced String:<\/strong> Hello, Java!<br \/>\n<strong>String representation:<\/strong> Hello, World!<\/p>\n<h3>Conclusion<\/h3>\n<p>In summary, StringBuilder in Java provides an efficient and convenient way to modify strings without creating multiple String objects. Its mutable nature makes it well-suited for scenarios where string manipulation is required frequently. The various methods, such as append, insert, delete, replace, etc., allow easy modification of character sequences.<\/p>\n<p>However, Java StringBuilder lacks synchronization and is not thread-safe. StringBuffer is more appropriate despite being slower for multithreaded environments requiring thread safety. In single-threaded contexts, though, StringBuilder is generally preferred over StringBuffer for performance reasons.<\/p>\n<p>Strings&#8217; immutability provides some advantages in terms of security and concurrency. But when mutability is needed, StringBuilder emerges as the right choice with its mix of efficiency and mutable character sequences. Used judiciously, it enables optimized string handling in Java applications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The StringBuilder class in Java enables the creation of adjustable sequences of characters. Unlike immutable Strings, StringBuilder allows modifying the character content after creation. This makes StringBuilder worthwhile when you frequently change the string&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":134204,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[7345,31126,31128,31078,8152,33197,31127],"class_list":["post-123461","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java","tag-java-stringbuilder-class","tag-java-stringbuilder-class-with-examples","tag-java-tutorials","tag-learn-java","tag-stringbuilder-class","tag-stringbuilder-class-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>StringBuilder Class in Java with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"StringBuilder in Java provides an efficient and convenient way to modify strings without creating multiple String objects.\" \/>\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-stringbuilder-class\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"StringBuilder Class in Java with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"StringBuilder in Java provides an efficient and convenient way to modify strings without creating multiple String objects.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/\" \/>\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-13T12:30:48+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-13T12:41:28+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-builder-class.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":"StringBuilder Class in Java with Examples - DataFlair","description":"StringBuilder in Java provides an efficient and convenient way to modify strings without creating multiple String objects.","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-stringbuilder-class\/","og_locale":"en_US","og_type":"article","og_title":"StringBuilder Class in Java with Examples - DataFlair","og_description":"StringBuilder in Java provides an efficient and convenient way to modify strings without creating multiple String objects.","og_url":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-11-13T12:30:48+00:00","article_modified_time":"2024-11-13T12:41:28+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-builder-class.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-stringbuilder-class\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"StringBuilder Class in Java with Examples","datePublished":"2024-11-13T12:30:48+00:00","dateModified":"2024-11-13T12:41:28+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/"},"wordCount":521,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-builder-class.webp","keywords":["Java","java stringbuilder class","java StringBuilder class with examples","java tutorials","Learn Java","stringbuilder class","StringBuilder class in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/","url":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/","name":"StringBuilder Class in Java with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-builder-class.webp","datePublished":"2024-11-13T12:30:48+00:00","dateModified":"2024-11-13T12:41:28+00:00","description":"StringBuilder in Java provides an efficient and convenient way to modify strings without creating multiple String objects.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-builder-class.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-builder-class.webp","width":1200,"height":628,"caption":"java string builder class"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-stringbuilder-class\/#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":"StringBuilder Class in Java 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\/123461","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=123461"}],"version-history":[{"count":7,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123461\/revisions"}],"predecessor-version":[{"id":143612,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123461\/revisions\/143612"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/134204"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=123461"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=123461"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=123461"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}