

{"id":126638,"date":"2025-12-01T18:00:56","date_gmt":"2025-12-01T12:30:56","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=126638"},"modified":"2025-12-01T18:43:47","modified_gmt":"2025-12-01T13:13:47","slug":"java-string-substring-method","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/","title":{"rendered":"Java String substring() Method with Examples"},"content":{"rendered":"<p>The substring() method of the Java String class is a commonly used string manipulation method. It allows extracting a substring from a larger string by specifying the beginning and ending indices. In this article, we will take an in-depth look at how the substring() works and how it can be used.<\/p>\n<p><strong>The substring() method is defined in the String class and has two variants:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">String substring(int beginIndex)\r\nString substring(int beginIndex, int endIndex)\r\n<\/pre>\n<p>The first version takes a single int parameter, beginIndex, that specifies the starting index of the substring. The substring returned will be from beginIndex to the end of the original string.<\/p>\n<p>The second version takes two int parameters &#8211; beginIndex and endIndex. This returns the substring from beginIndex to endIndex-1.<\/p>\n<p>Note that the endIndex is exclusive, meaning the character at endIndex is not included in the returned substring. This follows Java&#8217;s convention for specifying a range: the beginning index is inclusive, while the ending index is exclusive.<\/p>\n<h3>Internal Implementation of Java substring(int beginIndex)<\/h3>\n<p><strong>Here is a look at a simplified implementation of the single-parameter substring() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public String substring(int beginIndex) {\r\n  if (beginIndex &lt; 0 || beginIndex &gt; value.length()) {\r\n    throw new StringIndexOutOfBoundsException(beginIndex);\r\n  }\r\n        \r\n  int subLen = value.length() - beginIndex;\r\n  char[] newValue = Arrays.copyOfRange(value, beginIndex, subLen);\r\n  return new String(newValue);\r\n}<\/pre>\n<p>This performs some sanity checking on beginIndex to ensure it is within bounds. If not, a StringIndexOutOfBoundsException is thrown.<\/p>\n<p>It then calculates the length of the substring, which is from beginIndex to the end of the original string. The substring is created by copying the range from the internal character array (value) into a new array using copyOfRange(). This new array is then used to construct the String to return.<\/p>\n<h3>Internal Implementation of Java substring(int beginIndex, int endIndex)<\/h3>\n<p><strong>The implementation of the two-parameter version is similar:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public String substring(int beginIndex, int endIndex) {\r\n  if (beginIndex &lt; 0 || endIndex &gt; value.length() || beginIndex &gt; endIndex) {\r\n    throw new StringIndexOutOfBoundsException();\r\n  }\r\n  \r\n  int subLen = endIndex - beginIndex;\r\n  char[] newValue = Arrays.copyOfRange(value, beginIndex, subLen);\r\n  return new String(newValue);\r\n}<\/pre>\n<p>It does validity checks on the passed indices to catch any bad values. The length is calculated as endIndex &#8211; beginIndex. The character range is copied over into a new array, same as before.<\/p>\n<p>One difference is that it throws a more generic StringIndexOutOfBoundsException on invalid indices.<\/p>\n<h3>Examples of Java String substring()<\/h3>\n<p><strong>Let&#8217;s look at some examples of using substring() in Java:<\/strong><\/p>\n<h4>Example 1: Extracting a substring with begin and end indices<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class SubstringExample {\r\n    public static void main(String[] args) {\r\n        String str = \"HelloWorld\";\r\n        String sub = str.substring(2, 7);\r\n        System.out.println(sub); \/\/ Output: lloWo\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nlloWo<\/p>\n<p>Here we extract a substring from index 2 (inclusive) to index 7 (exclusive), so it prints &#8220;lloWo&#8221;.<\/p>\n<h4>Example 2: Extracting a substring from the beginning index to the end<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class SubstringExample {\r\n    public static void main(String[] args) {\r\n        String str = \"JavaRules\";\r\n        String sub = str.substring(4);\r\n        System.out.println(sub); \/\/ Output: Rules\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nRules<\/p>\n<p>Passing only the starting index returns the substring from that index to the end of the original string.<\/p>\n<h3>Applications of Java substring()<\/h3>\n<p><strong>Let&#8217;s see some practical examples of using substring():<\/strong><\/p>\n<h4>Extracting surnames from full names:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class SurnameExtraction {\r\n    public static void main(String[] args) {\r\n        String fullName = \"Robert Downey Jr\";\r\n        int index = fullName.lastIndexOf(' ');\r\n        String surname = fullName.substring(index + 1);\r\n        System.out.println(surname); \/\/ Output: Downey\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nDowney<\/p>\n<h4>Checking if a string is a palindrome:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class PalindromeCheck {\r\n    public static void main(String[] args) {\r\n        String word = \"racecar\";\r\n        String reversed = new StringBuilder(word).reverse().toString();\r\n\r\n        if (word.equals(reversed)) {\r\n            System.out.println(word + \" is a palindrome\");\r\n        }\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nracecar is a palindrome<\/p>\n<h3>Conclusion<\/h3>\n<p>To sum up, the Java String. substring() method is a versatile tool for extracting and manipulating substrings. It provides developers with the flexibility to specify both the start and end points of the desired substring using two parameter variants. The method&#8217;s internal implementation ensures proper bounds checking and adheres to Java&#8217;s exclusive-end-index convention.<\/p>\n<p>With practical applications ranging from extracting surnames to checking for palindromes, substring() remains a valuable feature in Java&#8217;s string manipulation toolkit, enhancing its overall string-processing versatility.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The substring() method of the Java String class is a commonly used string manipulation method. It allows extracting a substring from a larger string by specifying the beginning and ending indices. In this article,&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":134357,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[7345,31124,31246,31248,31078,8152,31125,31245,31247,31249],"class_list":["post-126638","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-method","tag-java-tutorials","tag-learn-java","tag-string-substring-method","tag-string-substring-method-in-java","tag-substring-method","tag-substring-method-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java String substring() Method with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"The Java String substring() method is a versatile tool for extracting and manipulating substrings within strings.\" \/>\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-substring-method\/\" \/>\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 Java String substring() method is a versatile tool for extracting and manipulating substrings within strings.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-string-substring-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=\"2025-12-01T12:30:56+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-12-01T13:13:47+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-substring.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 Java String substring() method is a versatile tool for extracting and manipulating substrings within strings.","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-substring-method\/","og_locale":"en_US","og_type":"article","og_title":"Java String substring() Method with Examples - DataFlair","og_description":"The Java String substring() method is a versatile tool for extracting and manipulating substrings within strings.","og_url":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2025-12-01T12:30:56+00:00","article_modified_time":"2025-12-01T13:13:47+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-substring.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-substring-method\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"Java String substring() Method with Examples","datePublished":"2025-12-01T12:30:56+00:00","dateModified":"2025-12-01T13:13:47+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/"},"wordCount":500,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-substring.webp","keywords":["Java","java string substring() method","java string substring() method with examples","java substring() method","java tutorials","Learn Java","string substring() method","string substring() method in java","substring() method","substring() method in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-string-substring-method\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/","url":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/","name":"Java String substring() Method with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-substring.webp","datePublished":"2025-12-01T12:30:56+00:00","dateModified":"2025-12-01T13:13:47+00:00","description":"The Java String substring() method is a versatile tool for extracting and manipulating substrings within strings.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-string-substring-method\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-string-substring-method\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-substring.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-substring.webp","width":1200,"height":628,"caption":"java string substring()"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-string-substring-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 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\/126638","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=126638"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126638\/revisions"}],"predecessor-version":[{"id":147924,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/126638\/revisions\/147924"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/134357"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=126638"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=126638"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=126638"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}