Java String Substring() Method with Examples

May 02, 2023
Java String Substring Method With Examples



Call it string methods or string call APIs. They both function the same way and are also often used interchangeably.

In Java, strings are immutable objects. They can’t be tweaked or modified. A programmer can define the string in any way desired while forming, yet the liberty ends there. Further, Java adds every new string to its constant pool, which entails other immutable objects or constants like strings.

new java job roles

With the basics defined, let’s delve into the Java substring method to understand its functionalities, use cases, and applications with examples.

Java Substring Method Defined

The method is a string manipulation technique that allows developers to modify strings and counter constant immutability in Java. The Java substring method returns desired substring from a selected one as defined by index values. Remember, the index values in Java begin from 0, not 1.

Variants of Java Substring Method

Developers can choose from two Java substring method variants to modify or call strings. The first requires defining the beginning index, while the other needs both; the beginning and the end. Despite their differences, both function effectively and return a new string as a substring.

So, without further ado, let’s decode the first variant to understand better how the function works.

1) The beginIndex

The method returns a new substring with character length equals endIndex minus beginIndex. The output entails characters beginning from the specified one to the last one.

For example: “impossible”.substring(2) would return “possible“. The beginIndex is inclusive, so the character at index 2 is included in the substring.

Further, you will get IndexOutOfBoundsException if the beginIndex is less than zero or greater than the string length (beginIndex<0||> length of String).

beginIndex Example

public class SubstringExample{ 
public static void main(String args[]){ 
String s1="HelloWorld"; 
System.out.println(s1.substring(5,10));
System.out.println(s1.substring(0));

}}

Output:

World
HelloWorld

2) beginIndex and endIndex

The second method returns a new substring with the character length equal endIndex minus beginIndex. In this type, the latter is inclusive, while the former is exclusive.

For example: “impossible”.substring(2,5) would return “pos“.

Remember, you will receive IndexOutOfBoundsException when the beginIndex is less than zero OR beginIndex > endIndex OR endIndex is greater than the String.

beginIndex and endIndex Example

public class JavaExample{

  public static void main(String args[]) {

    String str= new String("TravelTheWorld");

    System.out.print("Substring starting from index 6: ");

    System.out.println(str.substring(6));

    System.out.print("Substring from beginIndex 6 till endIndex 9: ");

    System.out.println(str.substring(6, 9));

  }

}

Output:

Substring starting from index 6: TheWorld

Substring from beginIndex 6 till endIndex 9: The

Additional Examples of Java Substring Method

1) Prefix and Suffix Extraction

Java substring method is also commonly used to extract prefixes and suffixes from a string. Let’s say we have a list of names; the technique can help filter out the ones with a specific surname.

public class SubstringExample3  

{  

// main method 

public static void main(String argvs[]) 

{  

String str[] = 

{  

"Michael Adams", 

"Olivia Brown", 

"John Adams", 

"Emily Clark", 

"Patrick J. Adams", 

"Tracey Adams" 

"Grace Brown", 

"Cassie Smith"

};  

String surName = "Adams"; 

int surNameSize = surName.length(); 

int size = str.length; 

for(int j = 0; j < size; j++) 

{  

    int length = str[j].length(); 

    // extracting the surname 

    String subStr = str[j].substring(length - surNameSize); 

    // checks whether the surname is equal to "Adams" or not 

    if(subStr.equals(surName)) 

    {  

        System.out.println(str[j]); 

    }  

}  

  }  

}

Output

Michael Adams

John Adams

Patrick J. Adams

Tracey Adams

2) First and Last Character Exclusion

Java substring can also exclude the first and last characters from a string. Remember, as index values in Java begin from ‘0’, the first character would have an index value of ‘0’. For this, the command used is str.substring(1). 

In contrast, substring(0, str.length()-1) is the command used to exclude the last character from a string. The length() method is used to return desired string and str.length()-1 is used to exclude the last character from it.

Example:

public class JavaExample{

  public static void main(String args[]) {

    String str= new String("Switzerland");

    System.out.print("Substring after removing first character: ");

    System.out.println(str.substring(1));

    System.out.print("Substring after removing last character: ");

    System.out.println(str.substring(0, str.length()-1));

  }

}

Output

Substring after removing first character: witzerland

Substring after removing last character switzerland

A Short Recap

Java substring lets developers create new substrings on the go and effectively resolve issues pertaining to constant immutability.

Knowing the Java substring method, developers can now approach immutability smartly by working with newer substrings. Let’s revisit the must-remember points to become acquainted with Java substrings better.

1) There are two variants of the Java substring method.

2) The first method works with only the beginning parameter.

3) In beginIndex, the first character is inclusive.

4) The second method requires defining beginIndex and endIndex.

5) In the second one, the first character is inclusive but endIndex is exclusive.

Also Read: How To Use ArrayList Set In Java With Examples

new Java jobs



author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US