Strings are basically defined as an array of characters. In Java, objects of a String are immutable which means that a constant cannot be changed once created. Finding the substring of a string is a very common question asked in the Java interviews. So, I’ll explain how Substring in Java works.

Substring in Java: What is a substring in Java?

A part of a stringis called a Substring. In other words, substring is a subset of another string. The Java substring() method returns a new string that is a substring of this string. substring() method is an overloaded method.

Syntax: substring(//any one of the methods) { //body }

Example:

This is a clear example of a substring in Java. Here, the string is “Edureka” but when you break it down into blocks, it’s composed of substrings which finally compute the string.

Let’s move ahead and understand the different methods under substring().

Substring in Java: Different methods under substring

There are basically two different methods under the substring() method. They are:

String substring(int begIndex)

String substring​(int beginIndex, int endIndex)

Let’s understand them in detail.

String substring(int begIndex)

This method has two variants and it returns a new string that is a substring of this string. The substring begins with a character at the specified index ‘beginIndex’ to the end of the string.

Syntax:public String substring(int begIndex)

Note: the index starts from ‘0’ which refer to the first character of String.

String substring​(int beginIndex, int endIndex)

This method has two variants and it returns a new string which is a substring of this string. The substring begins with a character at the specified index BeginIndex and extends to the end of the string or up to endIndex – 1 if another argument is present.

This brings us to the end of this article where we have learned about Substring in Java. Hope you are clear with all that has been shared with you in this tutorial.

Make sure you practice as much as possible and revert your experience.

If you found this article on “Substring in Java” relevant, check out theEdureka Java Certification Training,a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

We are here to help you with every step on your journey, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

If you come across any questions, feel free to ask all your questions in the comments section of “Substring in Java” and our team will be glad to answer.