The Wayback Machine - https://web.archive.org/web/20240921095929/https://www.geeksforgeeks.org/stringbuilder-substring-method-in-java-with-examples/
Open In App

StringBuilder substring() method in Java with examples

Last Updated : 19 Aug, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In StringBuilder class, there are two types of substring method depending upon the parameters passed to it.

substring(int start)

The substring(int start) method of StringBuilder class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character from index start to end of the old sequence.

Syntax:

public String substring(int start)

Parameters: This method accepts only one parameter start which is Integer type value refers to the start index of substring.

Return Value: This method returns the substring lie in the range start to end of old sequence.

Exception: This method throws StringIndexOutOfBoundsException if start is less than zero, or greater than the length of this object.

Below programs illustrate the StringBuilder substring() method:

Example 1:




// Java program to demonstrate
// the substring() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("GeeksForGeeks");
  
        // print string
        System.out.println("String contains = "
                           + str);
  
        // get substring start from index 5
        // using substring() and print results
        System.out.println("SubSequence = "
                           + str.substring(5));
    }
}


Output:

String contains = GeeksForGeeks
SubSequence = ForGeeks

Example 2: To demonstrate StringIndexOutOfBoundsException




// Java program to demonstrate
// Exception thrown by the substring() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("Indian Team Played Well");
  
        try {
            // get substring starts from index -7
            // using substring() and print
            str.substring(-7);
        }
  
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}


Output:

Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -7

substring(int start, int end)

The substring(int start, int end) method of StringBuilder class is the inbuilt method used to return a substring start from index start and extends to the index end-1 of this sequence. The string returned by this method contains all character from index start to index end-1 of the old sequence.

Syntax:

public String substring(int start)

Parameters: This method accepts two parameter start which is Integer type value refers to the start index of substring and end which is also a Integer type value refers to the end index of substring.

Return Value: This method returns the substring lie in the range index start to index end-1 of old sequence.

Exception: This method throws StringIndexOutOfBoundsException if start or end are negative or greater than length(), or start is greater than end.

Below programs illustrate the StringBuilder.substring() method:

Example 1:




// Java program to demonstrate
// the substring() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("GeeksForGeeks");
  
        // print string
        System.out.println("String contains = " + str);
  
        // get substring start from index 5 to index 8
        // using substring() and print results
        System.out.println("SubSequence = "
                           + str.substring(5, 8));
    }
}


Output:

String contains = GeeksForGeeks
SubSequence = For

Example 2: To demonstrate StringIndexOutOfBoundsException




// Java program to demonstrate
// Exception thrown by the substring() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("Indian Team Played Well");
  
        try {
            // get substring starts from index 7
            // and end at index 3
            // using substring() and print
            str.substring(9, 3);
        }
  
        catch (Exception e) {
  
            System.out.println("Exception: " + e);
        }
    }
}


Output:

Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -6

References:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#substring(int, int)
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#substring(int)



Similar Reads

StringBuilder append() Method in Java With Examples
The java.lang.StringBuilder.append() method is used to append the string representation of some argument to the sequence. There are 13 ways/forms in which the append() method can be used by the passing of various types of arguments: StringBuilder append(boolean a) :The java.lang.StringBuilder.append(boolean a) is an inbuilt method in Java which is
13 min read
StringBuilder offsetByCodePoints() method in Java with Examples
The offsetByCodePoints() method of StringBuilder class returns the index within this String contained by StringBuilder that is offset from the index passed as parameter by codePointOffset code points. Unpaired surrogates lies between index and codePointOffset count as one code point each. Syntax: public int offsetByCodePoints(int index, int codePoi
2 min read
StringBuilder toString() method in Java with Examples
The toString() method of the StringBuilder class is the inbuilt method used to return a string representing the data contained by StringBuilder Object. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString(). Subsequent changes to this sequence contained b
3 min read
StringBuilder trimToSize() method in Java with Examples
The trimToSize() method of StringBuilder class is the inbuilt method used to trims the capacity used for the character sequence of StringBuilder object. If the buffer used by StringBuilder object is larger than necessary to hold its current sequence of characters, then this method is called to resize the StringBuilder object for converting this obj
2 min read
StringBuilder appendCodePoint() method in Java with Examples
The appendCodePoint(int codePoint) method of StringBuilder class is the inbuilt method used to append the string representation of the codePoint argument to this sequence. The argument is appended to this StringBuilder content and length of the object is increased by Character.charCount(codePoint). The effect is the same as if the int value in para
2 min read
StringBuilder lastIndexOf() method in Java with Examples
In StringBuilder class, there are two types of lastIndexOf() method depending upon the parameters passed to it. lastIndexOf(String str) The lastIndexOf(String str) method of StringBuilder class is the inbuilt method used to return the index within the String for last occurrence of passed substring as parameter. The last occurrence of the empty stri
4 min read
StringBuilder indexOf() method in Java with Examples
In StringBuilder class, there are two types of indexOf() method depending upon the parameters passed to it. indexOf(String str) The indexOf(String str) method of StringBuilder class is the inbuilt method used to return the index within the String for first occurrence of passed substring as parameter. If substring str is not present then -1 is retur
4 min read
Matcher appendTail(StringBuilder) method in Java with Examples
The appendTail(StringBuilder) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and appends it to the given StringBuilder at the tail position. Syntax: public StringBuilder appendTail(StringBuilder builder) Parameters: This method takes a parameter builder which is the StringBuilder that stores the t
2 min read
Matcher appendReplacement(StringBuilder, String) method in Java with Examples
The appendReplacement(StringBuilder, String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public Matcher appendReplacement(StringBuilder builder, String stringToBeReplaced) Parameters: This method takes two parameters: builde
3 min read
StringBuilder charAt() in Java with Examples
The charAt(int index) method of StringBuilder Class is used to return the character at the specified index of String contained by StringBuilder Object. The index value should lie between 0 and length()-1. Syntax: public char charAt(int index) Parameters: This method accepts one int type parameter index which represents index of the character to be
3 min read
StringBuilder codePointAt() in Java with Examples
The codePointAt(int index) method of StringBuilder class takes an index as a parameter and returns a character unicode point at that index in String contained by StringBuilder or we can say charPointAt() method returns the "unicode number" of the character at that index. The index refers to char values (Unicode code units) and the value of index mu
4 min read
StringBuilder delete() in Java with Examples
The delete(int start, int end) method of StringBuilder class removes the characters starting from index start to index end-1 from String contained by StringBuilder. This method takes two indexes as a parameter first start represents index of the first character and endIndex represents index after the last character of the substring to be removed fr
3 min read
StringBuilder codePointCount() in Java with Examples
The codePointCount() method of StringBuilder class returns the number of Unicode code points in the specified text range in String contained by StringBuilder. This method takes two indexes as a parameter- first beginIndex which represents index of the first character of the text range and endIndex which represents index after the last character of
3 min read
StringBuilder capacity() in Java with Examples
The capacity() method of StringBuilder Class is used to return the current capacity of StringBUilder object. The capacity is the amount of storage available to insert new characters.Syntax: public int capacity() Return Value: This method returns the current capacity of StringBuilder Class.Below programs demonstrate the capacity() method of StringBu
2 min read
StringBuilder codePointBefore() in Java with Examples
The codePointBefore() method of StringBuilder class takes an index as a parameter and returns the "Unicode number" of the character before the specified index in String contained by StringBuilder. The index refers to char values (Unicode code units) and the value of index must lie between 0 to length-1. If the char value at (index - 1) is in the lo
2 min read
StringBuilder deleteCharAt() in Java with Examples
The deleteCharAt(int index) method of StringBuilder class remove the character at the given index from String contained by StringBuilder. This method takes index as a parameter which represents the index of char we want to remove and returns the remaining String as StringBuilder Object. This StringBuilder is shortened by one char after application
3 min read
StringBuilder ensureCapacity() in Java with Examples
The ensureCapacity(int minimumCapacity) method of StringBuilder class helps us to ensures the capacity is at least equal to the specified minimumCapacity passed as the parameter to the method. If the current capacity of StringBuilder is less than the argument minimumCapacity, then a new internal array is allocated with greater capacity. If the mini
2 min read
StringBuilder getChars() in Java with Examples
The getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method of StringBuilder class copies the characters starting at the given index:srcBegin to index:srcEnd-1 from String contained by StringBuilder into an array of char passed as parameter to function. The characters are copied from StringBuilder into the array dst[] starting at index:
3 min read
StringBuilder length() in Java with Examples
The length() method of StringBuilder class returns the number of character the StringBuilder object contains. The length of the sequence of characters currently represented by this StringBuilder object is returned by this method. Syntax: public int length() Return Value: This method returns length of sequence of characters contained by StringBuilde
2 min read
StringBuilder replace() in Java with Examples
The replace(int start, int end, String str) method of StringBuilder class is used to replace the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified index start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. At first, the
3 min read
StringBuilder setCharAt() in Java with Examples
The setCharAt(int index, char ch) method of StringBuilder class is used to set the character at the position index passed as ch. This method changes the old sequence to represents a new sequence which is identical to old sequence only difference is a new character ch is present at position index. The index argument must be greater than or equal to
2 min read
StringBuilder reverse() in Java with Examples
The reverse() method of StringBuilder is used to reverse the characters in the StringBuilder. The method helps to this character sequence to be replaced by the reverse of the sequence. Syntax: public java.lang.AbstractStringBuilder reverse() Returns: This method returns StringBuilder object after reversing the characters. Below programs illustrate
1 min read
StringBuilder setLength() in Java with Examples
The setLength(int newLength) method of StringBuilder is used to set the length of the character sequence equal to newLength.For every index k greater than 0 and less than newLength. If the newLength passed as argument is less than the old length, the old length is changed to the newLength.If the newLength passed as argument is greater than or equal
3 min read
StringBuilder subSequence() in Java with Examples
The subSequence(int start, int end) method of StringBuilder class is the inbuilt method used to return a subsequence of characters lie between index start and end-1 of this sequence. The subsequence starts with the char value at the index start and ends with the char value at (end-1). The length of the returned subsequence is end-start. So if start
3 min read
StringBuilder Class in Java with Examples
StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters. The function of StringBuilder is very much similar to the StringBuffer class, as both of them
6 min read
When to use Rope over StringBuilder in Java?
What are Ropes? Rope is a binary tree data structure where each node except the leaf contains the number of characters present to the left of the node. They are mainly used by text editors to store and manipulate large strings. It provides different string operations such as append, insert and delete in a faster and more efficient way. Ropes work m
3 min read
Difference Between StringBuffer and StringBuilder in Java
Strings in Java are the objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. However, java provides multiple classes through which strings can be used. Two such classes are StringBuffer and StringBuilder.
4 min read
String vs StringBuilder vs StringBuffer in Java
A string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created. Initializing a String is one of the important pillars required as a pre-requisite with deeper understanding. Comparison between String, StringBuilder, and StringBufferFeature String StringBuilder StringBuffer Int
7 min read
When to use StringJoiner over StringBuilder?
Prerequisite: StringJoinerStringJoiner is very useful, when you need to join Strings in a Stream. Task : Suppose we want the string "[George:Sally:Fred]", where we have given a string array that contains "George", "Sally" and "Fred".StringJoiner provide add(String str) method to concatenate the strings based on supplied delimiter,prefix and suffix
2 min read
StringBuffer substring() method in Java with Examples
In StringBuffer class, there are two types of substring method depending upon the parameters passed to it. substring(int start) The substring(int start) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character f
3 min read
Practice Tags :