In this article, we’ll start by defining what a substring is? A substring is a contiguous sequence of characters in a string, or put another way, it’s a part of a string. It can be the whole string as well. For example, consider the below string:
“SoftwareTestingo is a dedicated blog for learners”
Post On: | String Substring Method in Java |
Post Type: | Java Tutorials |
Published On: | www.softwaretestingo.com |
Applicable For: | Freshers & Experience |
Get Updates: | SoftwareTestingo Telegram Group |
The word “Blog” is a substring of the above string because it is a continuous sequence of characters. However, the word “STestingo” is not a substring because it is not continuous in the given string.
So, you can say that a substring is a subset of the string.
Methods Of substring()
There are two methods of substring() methods available. In this guide, we will see how to use this method with the help of examples.
String substring(): This method takes the starting index of a string and returns a new substring that begins at that startIndex. The range of the substring goes from the startIndex (including) to the end of the string.
package com.SoftwareTestingo.String; public class SubStringExample1 { public static void main(String[] args) { // Initializing String String Str = new String("Welcome to SoftwareTestingo"); System.out.println("The Substring is: "+Str.substring(11)); } }
String substring(begIndex, endIndex): The substring method can also take two parameters for the starting index and ending index. This will return a new string that is a substring of the original string, starting from the startIndex and ending at endIndex – 1.
package com.SoftwareTestingo.String; public class SubStringExample2 { public static void main(String[] args) { // Initializing String String Str = new String("Welcome to SoftwareTestingo"); System.out.println("The Substring is: "+Str.substring(0,7)); } }
Conclusions:
We have now reached the end of this article where we learned about Substring in Java. I hope you are now clear with all that has been shared with you in this tutorial.
If you have any questions, don’t hesitate to ask them in the comments section below and our team will be more than happy to answer them for you.
Leave a Reply