A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/substring-in-java/ below:

Java String substring() Method - GeeksforGeeks

Java String substring() Method

Last Updated : 11 Apr, 2025

Try it on GfG Practice

In Java, the substring() method of the String class returns a substring from the given string. This method is most useful when you deal with text manipulation, parsing, or data extraction.

Syntax of String substring() Method

public String substring(int beginIndex);

public String substring(int beginIndex, int endIndex);

Parameters:

Return Type:

Exceptions:

Note: If we pass the start index and endIndex with the same value so it will return an empty substring ("").

Example 1: Java program to extract a substring using substring(int beginIndex).

Java
// Java program to show the use of
// substring(int begIndex)

public class Geeks {

    public static void main(String[] args)
    {

        String s = "GeeksforGeeks";

        // Extracting substring starting from index 8
        String sub = s.substring(8);

        // printing the substring
        System.out.println("Substring: " + sub);
    }
}

Explanation: In the above code example, we use the substring(int beginIndex) method and specify the start index which is 8 and it didn't specified the end index. So it will make substring from end of the given string and we get the substring as "Geeks".

Diagramatic Representation:

Java Substring

Example 2: Java program to extract a substring from specified start index to specified end index using substring(int beginIndex, int endIndex).

Java
// Java program to show the use of
// substring(int begIndex, int endIndex)

public class Geeks 
{

    public static void main(String[] args)
    {

        String s = "Welcome to GeeksforGeeks";

        // Extract substring from index 0(inclusive)
        // to 7 (exclusive)
        String sub = s.substring(0, 7);

        // printing the substring
        System.out.println("Substring: " + sub);
    }
}

Output
Substring: Welcome

Explanation: In the above example, we use the substring(beginIndex, endIndex) the substring starts at index 0 and ends at index 7, but the character at index 7 is excluded.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4