English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java String substring() method extracts a substring from the string and returns it.
The syntax of substring() method is:
string.substring(int startIndex, int endIndex)
The substring() method has two parameters.
startIndex - Start index
endIndex (Optional)-End index
The substring() method returns a substring from the given string.
The substring exists with the character at startIndex and extends to the index endIndex - 1of the characters.
If endIndex is not passed, the substring exists with the character at the specified index and extends to the end of the string.
Note:If startIndex or endIndex is negative or greater than the length of the string, an error will occur. An error will also occur if startIndex is greater than endIndex.
class Main { public static void main(String[] args) { String str1 = "program"; //from the first character to the end System.out.println(str1.substring(0)); // program //from the fourth character to the end System.out.println(str1.substring(3)); // gram } }
class Main { public static void main(String[] args) { String str1 = "program"; //from the first character to the seventh character System.out.println(str1.substring(0, 7)); // program //from1to5character System.out.println(str1.substring(0, 5)); // progr //from4to5character System.out.println(str1.substring(3, 5)); // gr } }
If you need to find the index of the first occurrence of a specified substring in a given string, useJava String indexOf() Method.