Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. String.substring()

String.substring()

A method that extracts a portion of a string and returns it as a new string. Specifying only the start index extracts from that position to the end; specifying an end index as well extracts up to (but not including) that position.

Syntax

// Extracts from the start index to the end of the string.
str.substring(int beginIndex);

// Extracts from the start index up to (but not including) the end index.
str.substring(int beginIndex, int endIndex);

Methods

MethodDescription
substring(int beginIndex)Returns the substring from the position of beginIndex to the end of the string. Indexes are zero-based.
substring(int beginIndex, int endIndex)Returns the substring from beginIndex up to (but not including) endIndex. The character at endIndex is not included.

Sample Code

// Extracts from the start index to the end of the string.
String str = "Hello, Java!";
System.out.println(str.substring(7)); // Prints "Java!"

// Extracts a range by specifying start and end indexes.
System.out.println(str.substring(0, 5)); // Prints "Hello"

// Extracts the year, month, and day from a date string.
String date = "2025-06-15";
String year  = date.substring(0, 4); // "2025"
String month = date.substring(5, 7); // "06"
String day   = date.substring(8);    // "15"
System.out.println(year + "/" + month + "/" + day);
// Prints "2025/06/15"

// Combines with indexOf() to extract dynamically.
String email = "user@example.com";
int atIndex = email.indexOf("@");
String domain = email.substring(atIndex + 1); // "example.com"
System.out.println(domain);

// Extracts the last 3 characters.
String filename = "report.pdf";
String ext = filename.substring(filename.length() - 3); // "pdf"
System.out.println(ext);

Notes

substring() extracts a portion of a string and returns it as a new string. Indexes are zero-based, and the character at the end index is not included in the result. For example, substring(0, 5) returns characters at positions 0 through 4.

If the index is negative, beginIndex is greater than endIndex, or the index exceeds the length of the string, a StringIndexOutOfBoundsException is thrown. Use length() to check the string length beforehand to avoid this.

To get the length of a string, see length() / charAt(). To combine substring extraction with searching, see indexOf() / contains().

If you find any errors or copyright issues, please .