Introduction
Strings are one of the most commonly used data structures. One must be fluent with string operations to crack any coding interview. There are various operations that can be performed on strings. In this blog, we will learn how we can get substrings from a string using the substring() method in Java.

About string substring()
The string substring() is a method of the String class which is used to get a substring of the given string. Substring() has two parameters, namely startIndex and endIndex. StartIndex gives us the starting position of the substring and endIndex gives us the ending position of the substring. startIndex is compulsory and endIndex if optional. If endIndex is not given, string substring() will return the whole string from the starting index.

Syntax of string substring()
The syntax of substring() method is:
If endIndex is not given
public String substring(int startIndex)
If endIndex is given
public String substring(int startIndex, int endIndex)
Parameters of string substring()
There are two parameters that are passed in string substring().
startIndex: It gives us the starting position of the substring.
endIndex: It gives us the ending position of the substring. It is optional and If endIndex is not given string substring() will return each character of the string from the startIndex.
String substring() return value
String substring() returns the desired substring of the given string. The returned substring begins with the character at startIndex and end with the character at endIndex - 1.
String substring() will give an error if:
- startIndex or endIndex is negative.
- endIndex is smaller than startIndex.
- If startIndex or endIndex is larger than the string’s length.