We may not have the course you’re looking for. If you enquire or give us a call on +32 35001305 and speak to our training experts, we may still be able to help with your training requirements.
Training Outcomes Within Your Budget!
We ensure quality, budget-alignment, and timely delivery by our expert instructors.
Do you want to learn how to get a part of a string in Java? Do you want to know how the substring() method works and what are its variants? Do you want to see some examples and applications of Substring in Java? If you answered yes to any of these questions, then this blog is for you.
In this blog, we will cover everything you need to know about Substring in Java. We will explain what a substring is, how to use the substring () method, what are the parameters and return values of the method, and how to handle exceptions and errors. We will also show you some code snippets and output of the method, as well as some practical uses of Substring in Java.
Table of Contents
1) Substring definition in Java
2) Ways to get a Substring
3) Internal Implementation of Substring Function in Java
4) Example of Internal Implementation
5) Use cases of Substring
6) Conclusion
Substring definition in Java
A string extracted from a larger string is known as a Substring. They come under the class of java.lang.String. A built-in method known as substring() is available in the String class of Java that extracts a substring from the given string where the index values are passed as an argument. The startIndex value of a Java substring is considered when the compiler compiles a code, whereas the endIndex is optional and therefore neglected.
In Java, strings are immutable. Therefore, when this startIndex is called and stored in an initialised variable, the output returns a new string, whereas the original string remains unchanged. For instance, consider a string named “programming language” then, there exist different substrings of this string like ‘program’, ‘ing’, ‘lang’, ‘language’, etc. The general syntax of calling a Substring in Java is given by:
string.substring (int startIndex, int endIndex)
The above syntax shows that string represents an object of the class String. The startIndex and endIndex, as discussed, are inputs to the function, of which only the startIndex is taken into account, and the endIndex is excluded. The above syntax will produce an error known as IndexOutofBoundsException in the following cases:
a) When endIndex has a smaller value than a startIndex.
b) When the index value of either the startIndex or the endIndex is greater than the length of the string.
c) When there exists a possibility of having a negative index value in both.
Ways to get a Substring
From the given string object, a Substring in Java can be extracted in two ways:
public string.substring (int startIndex)
A new String object is returned using this method, which will contain the substring of the main string whose output will depend on the input of startIndex. However, a point to be noted is that when the value of the startIndex is greater than the string length or holds a negative value.
We provide an example code to demonstrate this method:
public class SubstringDemo
{
public static void main(String[] args)
{
String str = "Hello, world!";
// Get a substring starting from index 7
String sub = str.substring(7);
// Print the original string and the substring
System.out.println("Original string: " + str);
System.out.println("Substring starting from index 7: " + sub);
}
}
Output:
Original string: Hello, world!
Substring starting from index 7: world!
In this program, we create a string str containing the text "Hello, world!". We then use the substring() method to extract a substring starting from index 7 (which corresponds to the letter "w" in the original string). This is done using the str.substring(7) method call, which returns a new string containing the remaining characters starting from index 7. We then print out both the original string and the extracted substring using System.out.println().
You can learn how to develop a web application using Java programming by signing up for our Web Development Using Java Training course now!
public string.substring (int startIndex, int endIndex)
This method shows two input variables – startIndex and endIndex as arguments to the substring function. Based on the input of these two variables, a new string object is returned that will contain the substring of the main string such that the indexes of the substring will be in between the startIndex and endIndex. The presence of the second argument variable will lead to starting of the substring from startIndex to endIndex-1.
We provide an example code to demonstrate this method:
public class SubstringDemo
{
public static void main(String[] args)
{
String str = "Hello World!";
// Get a substring starting from index 6 (inclusive) and ending at index 11 (exclusive)
String substr1 = str.substring(6, 11);
System.out.println(substr1); // Output: World
// Get a substring starting from index 0 (inclusive) and ending at index 5 (exclusive)
String substr2 = str.substring(0, 5);
System.out.println(substr2); // Output: Hello
}
}
Output:
World
Hello
In this program, we first create a String object called str and initialise it to "Hello World!". We then use the substring() method to get two different substrings from str. In the first call to substring(), we specify the beginning index as 6 (which corresponds to the letter 'W' in "World") and the ending index as 11 (which corresponds to the space character after "World"). The resulting substring is "World".
In the second call to substring(), we specify the beginning index as 0 (which corresponds to the letter 'H' in "Hello") and the ending index as 5 (which corresponds to the letter 'o' in "Hello"). The resulting substring is "Hello". Finally, we use System.out.println() to print out each substring to the console.
Learn to develop, understand and implement JavaScript with HTML by signing up for our JavaScript For Beginners course now!
Internal Implementation of Substring Function in Java
In Java, you can use the substring() function to get a part of a string that you want. The function creates a new string object and copies some characters from the original string object to the new one. The new string object has the characters from a certain position in the original string until the end or until another position. In this article, we’ll see how the substring() function works inside the Java String class.
How to Write Substring() Function:
public String substring(int startIndex)
public String substring(int startIndex, int endIndex)
The substring() function has two ways of writing it, depending on how many numbers you give it. The numbers are called parameters, and they tell the function where to start and end the substring. The first parameter, startIndex, is always needed, and it tells the function the position of the first character of the substring. The second parameter, endIndex, is optional, and it tells the function the position of the last character of the substring. If you don’t give an endIndex, the function will take all the characters from the startIndex to the end of the original string.
Example of Internal Implementation
The substring() function is defined in the String class in Java. When you call the substring() function on a string object, the JVM makes a new string object and copies the needed characters from the old string object to the new one.
Let’s see how the substring() function works:
public String substring(int startIndex) { if (startIndex < 0 || startIndex > value.length) { throw new StringIndexOutOfBoundsException(startIndex); } if (startIndex == 0) { return this; } else { return new String(value, startIndex, value.length - startIndex); } } public String substring(int startIndex, int endIndex) { if (startIndex < 0 || endIndex > value.length || startIndex > endIndex) { throw new StringIndexOutOfBoundsException(); } if (startIndex == 0 && endIndex == value.length) { return this; } else { return new String(value, startIndex, endIndex - startIndex); } } |
In the first version, the function has one parameter, startIndex. The function first checks if the startIndex is valid. If the startIndex is less than 0 or more than the length of the original string, it throws a StringIndexOutOfBoundsException. If the startIndex is 0, the function gives back the original string object. If the startIndex is valid, the function makes a new string object with the given range of characters from the old string object.
Use cases of Substring
We will discuss some of the cases where Substring in Java can be used:
1) Removal of unnecessary characters: It can also be used to remove unwanted characters from a string. For instance, if there is an input string whose phone number is of the form "(911) 777-7777", then a Substring can be used to recover the raw number by removing the parentheses, spaces, and hyphens.
2) Manipulate a String: It can also be used to manipulate strings in various ways. For instance, by using Substring, you can take out the first few characters of a string, convert any string to lowercase or uppercase, or in some cases, reverse the characters.
3) Validating a Password: A substring can also be used to validate passwords. For example, to check the presence of a minimum number of characters or the presence of uppercase and lowercase characters in a typical password.
4) Inspecting Substring presence: A Substring can be used to check if a specific substring is contained within a string. For example, if a string contains a list of email addresses, then a substring can be used to check the presence of a particular email address from the list.
5) String Parsing: A substring can be used to extract a specific portion of a string. For instance, if there exists a date whose format is "YYYY-MM-DD", then Substring can be used to extract each date entity.
Develop an understanding of JavaScript with our JavaScript for Beginners course. Join now!
Conclusion
After reading this blog, you will now be able to know what exactly a Substring Java is and its influence on a particular string input. Secondly, you will know the different ways of getting a Substring in Java and how substring functions can perform various operations on strings in Java.
Frequently Asked Questions
In Java, you can check if a string contains three characters by using the length() method to verify if the string's length is equal to 3. For example: boolean containsThree = str.length() == 3;
An example of a substring is extracting a portion of a string. For instance, in the string "hello world", a substring could be "world", obtained by specifying the starting index where "world" begins within the original string.
The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.
The Knowledge Academy offers various Java Trainings, including Java Programming, JavaScript for Beginners and Java Swing Development Training. These courses cater to different skill levels, providing comprehensive insights into How to Become a Java Developer.
Our Programming and DevOps blogs cover a range of topics related to Java, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Java Programming skills, The Knowledge Academy's diverse courses and informative blogs have you covered.
The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.
Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
Upcoming Programming & DevOps Resources Batches & Dates
Date
Mon 20th Jan 2025
Mon 3rd Mar 2025
Mon 12th May 2025
Mon 14th Jul 2025
Mon 22nd Sep 2025
Mon 17th Nov 2025