String’s substring method is used to fetch part of a String.It returns a new String which is substring of given String. substring is nothing but subset of given String.
There are two overloaded methods for substring.
Method Signature:
public String substring(int startIndex)
It returns a new String which is substring of given String from specified startIndex(Inclusive)
public String substring(int startIndex, int endIndex)
It returns a new String which is substring of given String from specified startIndex(Inclusive) to endIndex(Exclusive)
String’s index always starts with 0. In case of substring method, startIndex is always inclusive and endIndex is exclusive
String substring Example:
package org.arpit.java2blog;
public class StringSubStringExample {
public static void main(String[] args) {
String str1= "java2blog.com";
// using beginIndex
System.out.println(str1.substring(5));
// using beginIndex and endIndex
System.out.println(str1.substring(5,9));
}
}
When you run above program, you will get below output:
blog.com blog