Using the Substring Method in Java

In Java, the String class provides a substring() method that allows you to extract a portion of the string based on the provided indices. The method comes in two overloaded forms: The first form, substring, returns a substring starting from the beginIndex and extending to the end of the string. The second form, substring, returns a substring starting from the beginIndex and opening up to, but not including, the endIndex. It's essential to remember that the indices are 0-based; the start is inclusive, and the end is exclusive. In this Java Substring Example, a string is created, and portions of it are extracted using the substring() method. Click Execute to run the Java Substring Example online and see the result.
Using the Substring Method in Java Execute
public class SubstringDemo {
    public static void main(String[] args) {
        String str = "Programming";

        String sub1 = str.substring(4);
        System.out.println("Substring from index 4: " + sub1);

        String sub2 = str.substring(4, 7);
        System.out.println("Substring from index 4 to 7: " + sub2);
    }
}
Updated: Viewed: 39 times