by Dinesh Thakur

Programmers often need to retrieve an individual character or a group of characters (substring) from a string. For example: In a word processing program, when a part of string is copied or deleted. While charAt () method returns only a single character from a string, the substring () method in the String class can be used to obtain a substring from a string.

String substring(int beginIndex) : This method returns a new string that is a substring of the invoking string. The substring returned contains a copy of characters beginning from the specified index beginIndex and extends to the end of the string. For example,

S1.substring(3); // returns substring 'come'

String substring (int beginIndex, int endIndex) : This method is another version of previous method. It also returns a substring that begins at the specified begin Index and extends to the character at index endIndex-1. For example,

s1.substring(3,6); // returns substring "come".

public class SubstringMethods
{
     public static void main(String[] args)
   {     
      String sl = "Welcome" ;
      System.out.println("sl.substring(3) = " + sl.substring(3));
      System.out.println("substring(3,6) = " + sl.substring(3));
    }
}

String substring() in Java Example

class StrSubString

{
            public static void main(String args[])
            {
                        String k="Hello Dinesh";
                        String m="";
                        m=k.substring (6,12);
                        System.out.println(m);
            }
}

String substring() in Java Example