Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
HowToDoInJava
  • Java
  • Spring AI
  • Spring Boot
  • Hibernate
  • JUnit 5
  • Interview

Java String substring()

Learn to find the substring of a string between the begin and end indices, and valid values for both indices with examples.

Lokesh Gupta

January 10, 2023

Java String class
Java String
java string substring

Learn to get a substring from from given String in Java between the two indices. Note that String is character array based type and the first character of String is at 0 index.

If we store a String “Hello World” in Java, then it creates a character array of size 11 in the memory to store all the characters of the String value.

String str = "Hello World";

The following is a pictorial representation of the array in memory.

1. String.substring() API

The String.substring() in Java returns a new String that is a substring of the given string that begins from startIndex to an optional endIndex. These indices determine the substring position within the original string.

The substring() method takes two arguments:

  • beginIndex: the beginning index of the substring. This index position is inclusive, i.e. the character at the specified index is included in the substring.
  • endIndex: the end index of the substring. This index position is exclusive, i.e. the character at the specified index is NOT included in the substring.
String substring(int beginIndex)
String substring​(int beginIndex, int endIndex)

The method returns the substring between the valid start and end indices. If the indices are not valid then we can get IndexOutOfBoundsException error in the runtime.

2. Substring Examples

Let us see a few examples to understand how the substring() method works.

2.1. Using beginIndex and endIndex

Pass both indices (begin and end indices) when we need to find a substring starting from the given index position to the given end index position. Please note that:

  • The beginIndex can be greater than the endIndex.
  • Both indices must be greater than or equal to 0.
  • Both indices must be less than the length of the string.
  • If we pass the same index for both arguments, an empty string is returned.

In the following program, we are finding the substring between the indices 0 and 5. Remember that end index is exclusive, so the character at end index is not included in the substring. In this case, the character at end index is whitespace.

Similarily, we can search for the substring between indices 2 to 8.

Assertions.assertEquals("llo Wo", str.substring(2, 8));

2.2. Using only beginIndex

When we do not pass the endIndex argument, the substring is taken up to the last character of the string. In other words, if not specified, the value of endIndex is always ‘string.length() – 1’.

In the following example, we are getting the substring from index position 6.

Assertions.assertEquals("World", str.substring(6));

3. IndexOutOfBoundsException

As mentioned earlier, if we pass an invalid index (such as negative index value) that does not exist in the character array, or the begin index is greater than end index then we will get the IndexOutOfBoundsException in runtime.

Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {   //invalid index
  str.substring(-1);
});

Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {  //begin index > end index
  str.substring(6, 4);
});

4. Conclusion

In this short Java tutorial, we learned to get the substring of a specified string using the begin and end indices. We learned the rules about valid index values, and begin index is inclusive and end index is exclusive.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

String Examples

  • String Constant Pool
  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • Align Left, Right, Center
  • Immutable Strings
  • StringJoiner
  • Split a string
  • Escape HTML
  • Unescape HTML
  • Convert to title case
  • Find duplicate words
  • Left pad a string
  • Right pad a string
  • Reverse recursively
  • Leading whitespaces
  • Remove whitespaces
  • Reverse words
  • Find duplicate characters
  • Get first 4 characters
  • Get last 4 characters
  • (123) 456-6789 Pattern
  • Interview Questions

String Methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

Table of Contents

  • 1. String.substring() API
  • 2. Substring Examples
    • 2.1. Using beginIndex and endIndex
    • 2.2. Using only beginIndex
  • 3. IndexOutOfBoundsException
  • 4. Conclusion
Photo of author

Lokesh Gupta

A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies. An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Follow on Twitter Portfolio

Previous

Java String lastIndexOf()

Next

Java String concat()

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

OOP

Regex

Maven

Logging

TypeScript

Python

Meta Links

About Us

Advertise

Contact Us

Privacy Policy

Our Blogs

REST API Tutorial

Follow On:

  • Github
  • LinkedIn
  • Twitter
  • Facebook
Copyright © 2026 | Sitemap