Java String substring() Method
This is one of the articles from our Java Tutorial for Beginners.
The Java String substring() Method
Syntax:
1 2 3 4 5 |
public String substring(int beginIndex) or public String substring(int beginIndex, int endIndex) |
When you set int beginIndex (for example: beginIndex number 3), the program copies all the information from that index number (in our case: 3) until and including the end.
When you set both int beginIndex and int endIndex (for example: beginIndex number 3 and endIndex 7), the program copies all the information from the beginning index number (in our case: 3) until, but not including the end index number (in our case: 7). In other words, the endIndex number is not included.
Keep in mind that index numbers start from zero. It will make more sense in practice.
Example
1 2 3 4 5 6 7 8 |
class Test { public static void main(String[] args) { String sentence ="I love Java"; System.out.println(sentence.substring(2)); System.out.println(sentence.substring(2,6)); } } |
If you run this code on your computer, you will see the following in the console:
love Java
love
You can find more articles in our Java Tutorial for Beginners.