How to Use Java String Class substring() Method

Function Description

The Java String class substring() method is used to get the substring of the string. The substring begins from the character specified at the begin-index to the end of the string or to the character specified at end-index.  In returned substring, character at begin-index is included while character at end-index is excluded.

In String class, substring() is an overloaded method. It has two substring() methods with different arguments to get substring of the string.

  1. substring() method without  specified end-index  : To get the substring starting from the character specified at begin-index to the end of the string
  2. substring() method with specified end-index : To get the substring starting from the character at specified begin-index to the character at specified endindex-1

Method  Signature

substring()  method without specified end-index:

public String substring(int beginIndex) {

substring()  method with specified end-index:

public String substring(int beginIndex, int endIndex) {

Parameters

beginIndex: int type parameter to get the character at beginIndex. Character at specified beginIndex parameter is included.

endIndex: int type parameter to get the character at the endIndex-1 position. Character at specified EndIndex parameter is excluded.

Return Type

Substring of the String

Exception

Throws IndexOutOfBoundsException if passing index value is negative or greater than the length of the String.

Examples of Java String Class substring()  Function

1.     Example of Java String Class substring() method without specified end-index

public static void main(String[] args) {

    String str1 = "Welcome to String class substring() function learning.";
   
    // return subString from begin index 11

    String subString1 = str1.substring(11);
 
    System.out.println("SubString from begin index 11 = '" + subString1 + "'");
   
    }

}
 

Output:

SubString from begin index 11 = 'String class substring() 
function learning.'

2.     Example of Java String Class substring() method with specified end-index 

public class ExampleStringSubString {
   
public static void main(String[] args) {

    String str1 = "Welcome to String class substring() function learning.";
   
    //return subString from begin index 0 to end index 7

    //begin index is included and end index is excluded

    String subString1 = str1.substring(0, 7);
   
    //return subString from begin index 11 to end index 22.

    //begin index is included and end index is excluded

    String subString2 = str1.substring(11,35);
   
 
    System.out.println("SubString from index 0 to 7 = "+subString1);

    System.out.println("SubString from index 11 to 16 = "+subString2);
   
    }
}

 
Output:

SubString from index 0 to 7 = Welcome

SubString from index 11 to 16 = String class substring()

3.     Example of Java String Class substring() method to throw Exception

public class ExampleStringSubString {
 
    public static void main(String[] args) {

       String str = "Welcome to String class substring() function learning.";
 
       // index value of last character dot(.)

       System.out.println("String index value : " + str.indexOf("."));
 
       // should throw exception as end index 85 is out of range

          String subString = str.substring(35, 85);
 
          System.out.println("SubString = " + subString);
 
    }
}
 

Output:

String index value : 53

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 85

    at java.lang.String.substring(String.java:1963)

    at com.java.test.ExampleStringSubString.main(ExampleStringSubString.java:12)

Other Methods of String Class

SequenceMethodDescription
1char charAt(int index)This method is used to return the character of the string at specified index. First character is at index 0 while last is at string length-1 . StringIndexOutOfBounds Exception is thrown if valid index value is not passed.
2int length()Returns the number of characters count  in  a string.
3static String format(String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s).
4static String format(Locale l, String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s) and locale.
5boolean contains(CharSequence s)Returns boolean value(true/false). It searches the given sequence of characters within the string and returns true/false accordingly. Characters will be case sensitive while searching in string.
6static String join(CharSequence delimiter, CharSequence… elements)Returns joined string. This method joins each passing String using the specified delimiter. It is a static method.
7static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)Returns the joined string. This method joins each passing string object of an iterate object using the specified delimiter and returns the concatenated string. It is a static method.
8boolean equals(Object another)Returns boolean value(true/false). It checks the equality of string with the passing object.
9boolean isEmpty()Returns boolean value(true/false). It returns true if the string is empty otherwise returns false.
10String concat(String str)Returns the concatenating string. It concatenates the passing string at the end of the string.
11String replace(char old, char new)Return the replaced string. It replaces all occurrences of the specified character with the new character.
12String replace(CharSequence old, CharSequence new)Return the replaced string. It replaces all occurrences of the specified Character sequence with the specified new Character sequence.
13String replaceAll(String regex, String replacement)Returns the replaced string. It replaces all occurrences of the sequence of characters with the given replacement string that are matching with the given regular expression.
14String replaceFirst(String regex, String replacement)Returns the replaced string. It replaces the first matching sequence of characters with the replacement string that matches with the given regular expression.
15static boolean equalsIgnoreCase(String another)Returns the boolean (true/false) value. It compares the passing string with string by ignoring the case. It  compares the content irrespective of lowercase or uppercase of the character(s).
16String[] split(String regex)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. String is breaked into strings from all  the matching regular expressions.
17String[] split(String regex, int limit)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. It breaks the string from all the matching regular expression upto the given limit.
18String intern()Returns an interned string. This method helps to compare two objects using == operator and checks in a string constant pool. it is faster for comparison.
19int indexOf(int ch)Returns the index value of first occurrence of the specified character within the string
20int indexOf(int ch, int fromIndex)Returns the index value of first occurrence of the specified character from the substring starting from specified index
21int indexOf(String substring)Returns the index value of first occurrence of the specified substring within the string.
22int indexOf(String substring, int fromIndex)Returns the index value of the first occurrence of the specified string within the substring starting from specified index to end of the string index.
23int lastIndexOf(int ch)Returns the index value of last occurrence of the specified character
24int lastIndexOf (int ch, int fromIndex)Returns the index value of last occurrence of the specified character, search starts at given fromIndex. 
25int lastIndexOf (String str)Returns the index value of last occurrence of the specified string.
26int lastIndexOf (String str, int fromIndexReturns the index value of last occurrence of the specified string, searches start from given fromIndex
27String toLowerCase()Returns all the characters of the string in lowercase .
28String toLowerCase(Locale l)Returns all the characters of the string in lowercase using specified locale.
29String toUpperCase()Returns all the characters of the string in uppercase.
30String toUpperCase(Locale l)Returns all the characters of the string in uppercase using specified locale.
31String trim()Returns the string after removing the white space from the beginning and end of the string.
32static String valueOf(int value)Return the converted string. It converts the objects and all primitive types of values into string. It is a static method.

In this article, we learned all about the substring() method of String class with examples. Apart from the substring() method, we got an idea about other String methods too. We will come up with more articles explaining other String methods with examples. For more details please click on the respective methods link.

This article was written by Renu Singh

14+ Years of experience in various phases of the software development life cycle. Specialties: Java/J2EE, Struts, Hibernate, JSF, JSP, Servlets, AJAX, Oracle, Oracle Knowledge, SQL Server 2000, DB2, EJB3.0. Companies Worked For: 1) Tata Consultancy Services 2) Infogain 3) TS Infotech 4) Daffodil Software Ltd.

Leave a Reply

Your email address will not be published. Required fields are marked *