How to use the substring() method of java.lang.String class in Java?

JavaObject Oriented ProgrammingProgramming

<p>The <strong>substring()</strong> method returns a String datatype which corresponds to the original String starting from the begin index until the end Index. If the end index is not specified, it is imperative that the <strong>endIndex&nbsp;</strong>is the String length. Since we are dealing with the String, the index starts at &#39;<strong>0&#39;</strong> <strong>position</strong>.</p><h2>Syntax</h2><pre class="prettyprint notranslate">public String substring(int beginIndex) public String substring(int beginIndex, int endIndex)</pre><p><strong>beginIndex:</strong> the starting index or position where we want to start to cut or substring our String.</p><p><strong>endIndex: &nbsp;&nbsp;</strong> the end index or position where we want to end our cutting or substring our String.</p><p>This method<strong>&nbsp;returns a String datatype&nbsp;</strong>which corresponds to the part of our string which we cut. If no <strong>endIndex&nbsp;</strong>is specified, then the end index is assumed to be<strong>&nbsp;String length -1</strong> and an <strong>IndexOutOfBoundsException&nbsp;</strong>is thrown if the <strong>beginIndex&nbsp;</strong><strong>is negative</strong> or it is <strong>larger than the length of the String.</strong></p><h2>Example</h2><p><a class="demo" href=" " rel="nofollow" target="_blank">Live Demo</a></p><pre class="prettyprint notranslate" style="">public class StringSubstringTest{ &nbsp; &nbsp;public static void main(String[] args) { &nbsp; &nbsp; &nbsp; String str = &quot;Welcome to Tutorials Point&quot;; &nbsp; &nbsp; &nbsp; System.out.println(str.substring(5)); &nbsp; &nbsp; &nbsp; System.out.println(str.substring(2, 5)); &nbsp; &nbsp; &nbsp; str.substring(6); &nbsp; &nbsp; &nbsp; System.out.println(&quot;str value: &quot;+ str); &nbsp; &nbsp; &nbsp; String str1 = str.substring(5); &nbsp; &nbsp; &nbsp; System.out.println(&quot;str1 value: &quot;+ str1); &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">me to Tutorials Point lco str value: Welcome to Tutorials Point str1 value: me to Tutorials Point</pre>
Updated on 07-Feb-2020 05:41:38