

{"id":123457,"date":"2024-11-06T18:00:45","date_gmt":"2024-11-06T12:30:45","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=123457"},"modified":"2024-11-06T19:16:00","modified_gmt":"2024-11-06T13:46:00","slug":"string-substring-method-in-java","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/","title":{"rendered":"Java String substring() Method with Examples"},"content":{"rendered":"<p>The substring() method in Java serves the purpose of extracting a portion of a String. It comes in two distinct variants. The first variant, String substring(int beginIndex), generates a new String that commences with the character at the specified beginIndex and continues to the end of the original String.<\/p>\n<p>The second variant, String substring(int beginIndex, int endIndex), creates a new String starting at beginIndex and extending to the character at endIndex &#8211; 1.<\/p>\n<p>In this article, we will delve into the syntax, parameters, and return values and provide examples for both forms of the substring() method. Additionally, we will explore the time and space complexities associated with this method and various common scenarios where substring extraction proves valuable.<\/p>\n<h2>Java String substring(int beginIndex)<\/h2>\n<p>The substring(int beginIndex) variant returns a new String that begins with the character at the specified beginIndex and extends to the end of the original String.<\/p>\n<p><strong>Syntax<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public String substring(int beginIndex)<\/pre>\n<p><strong>Parameters<\/strong><\/p>\n<p><strong>beginIndex &#8211;<\/strong> The begin index, inclusive. This is the starting index of the substring.<\/p>\n<p><strong>Return Value<\/strong><\/p>\n<p>This method returns a new String containing the extracted substring.<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class SubstringExample {\r\n    public static void main(String[] args) {\r\n        String s = \"HelloWorld\";\r\n        String sub = s.substring(5);\r\n        \r\n        System.out.println(sub);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nWorld<\/p>\n<p>With s.substring(5), the substring begins at index 5, which is &#8220;W,&#8221; and extends to the end of the string, resulting in &#8220;World&#8221; as the output.<\/p>\n<h3>Java String substring(int beginIndex, int endIndex)<\/h3>\n<p>The substring(int beginIndex, int endIndex) variant returns a new String that begins with the character at the specified beginIndex and extends to the character at index endIndex &#8211; 1.<\/p>\n<p><strong>Syntax<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public String substring(int beginIndex, int endIndex)<\/pre>\n<p><strong>Parameters<\/strong><\/p>\n<ul>\n<li><strong>beginIndex &#8211;<\/strong> The begin index, inclusive<\/li>\n<li><strong>endIndex &#8211;<\/strong> The end index, exclusive<\/li>\n<\/ul>\n<p><strong>Return Value<\/strong><\/p>\n<p>This method returns a new String containing the extracted substring.<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class SubstringExample {\r\n    public static void main(String[] args) {\r\n        String s = \"HelloWorld\";\r\n        String sub = s.substring(0, 5);\r\n        \r\n        System.out.println(sub);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nHello<\/p>\n<p>In this code, we use the substring() method with two arguments: s.substring(0, 5). It extracts the substring starting at index 0 (inclusive) and ending at index 5 (exclusive), resulting in &#8220;Hello&#8221; as the output.<\/p>\n<h3>Complexity<\/h3>\n<p><strong>Time Complexity:<\/strong> As we reference a part of the original String, the substring() method has a constant time complexity O(1).<\/p>\n<p><strong>Space Complexity:<\/strong> The substring() method creates a new String, therefore it has a space complexity of O(n) where n is the length of the substring.<\/p>\n<h3>Applications of substring() in Java<\/h3>\n<p><strong>Substring extraction using substring() is helpful in many scenarios:<\/strong><\/p>\n<ul>\n<li><strong>Extracting prefixes or suffixes &#8211;<\/strong> When we want to extract a prefix or suffix from a string, e.g. extracting the domain from an email address.<\/li>\n<li><strong>Parsing strings &#8211;<\/strong> Extracting relevant data from strings with fixed formats or mixed content. E.g. parsing log files.<\/li>\n<\/ul>\n<p><strong>Here is an example application to extract the domain from an email address:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class EmailParser {\r\n\r\n  public static String extractDomain(String email) {\r\n    \/\/ Find @ index  \r\n    int atIdx = email.indexOf('@');\r\n    \r\n    \/\/ Extract substring after @\r\n    String domain = email.substring(atIdx+1);\r\n    return domain;\r\n  }\r\n\r\n  public static void main(String[] args) {\r\n    String email = \"john@example.com\";\r\n    String domain = extractDomain(email);\r\n    System.out.println(domain);\r\n  }\r\n}<\/pre>\n<p>This code finds the index of &#8216;@&#8217; using indexOf() and then extracts the substring after that index as the domain.<\/p>\n<p><strong>Output:<\/strong><br \/>\nexample.com<\/p>\n<h3>Conclusion<\/h3>\n<p>Java&#8217;s substring() method is a helpful String manipulation tool for extracting substrings from a larger String. Its two variants allow extracting a substring given just a starting index or both a start and end index.<\/p>\n<p>Substring extraction has a constant time complexity, which makes it efficient even for large strings. The method has wide applicability for tasks like parsing strings, extracting affixes, and data cleaning. However, it does create a new String object, so it takes up additional memory proportional to the size of the extracted substring.<\/p>\n<p>Overall, substring() is a simple yet powerful method for manipulating substrings in Java. Understanding how to use it correctly can help write cleaner and more efficient string processing code.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The substring() method in Java serves the purpose of extracting a portion of a String. It comes in two distinct variants. The first variant, String substring(int beginIndex), generates a new String that commences with&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":124161,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[7345,31124,31246,31122,31078,8152,31125,31245,31123,31121],"class_list":["post-123457","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java","tag-java-string-substring-method","tag-java-string-substring-method-with-examples","tag-java-substring","tag-java-tutorials","tag-learn-java","tag-string-substring-method","tag-string-substring-method-in-java","tag-substring","tag-substring-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 substring() Method with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"The substring() method in Java is a useful String manipulation tool for extracting substrings from a larger 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\/string-substring-method-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java String substring() Method with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"The substring() method in Java is a useful String manipulation tool for extracting substrings from a larger String.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/\" \/>\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-06T12:30:45+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-06T13:46:00+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/substring-in-java.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 substring() Method with Examples - DataFlair","description":"The substring() method in Java is a useful String manipulation tool for extracting substrings from a larger 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\/string-substring-method-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Java String substring() Method with Examples - DataFlair","og_description":"The substring() method in Java is a useful String manipulation tool for extracting substrings from a larger String.","og_url":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-11-06T12:30:45+00:00","article_modified_time":"2024-11-06T13:46:00+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/substring-in-java.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\/string-substring-method-in-java\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"Java String substring() Method with Examples","datePublished":"2024-11-06T12:30:45+00:00","dateModified":"2024-11-06T13:46:00+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/"},"wordCount":569,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/substring-in-java.webp","keywords":["Java","java string substring() method","java string substring() method with examples","java substring","java tutorials","Learn Java","string substring() method","string substring() method in java","substring","substring in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/","url":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/","name":"Java String substring() Method with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/substring-in-java.webp","datePublished":"2024-11-06T12:30:45+00:00","dateModified":"2024-11-06T13:46:00+00:00","description":"The substring() method in Java is a useful String manipulation tool for extracting substrings from a larger String.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/substring-in-java.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/substring-in-java.webp","width":1200,"height":628,"caption":"substring in java"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/string-substring-method-in-java\/#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 substring() 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\/123457","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=123457"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123457\/revisions"}],"predecessor-version":[{"id":143575,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123457\/revisions\/143575"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/124161"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=123457"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=123457"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=123457"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}