The Java substring() method is used to extract a portion of a string. It is part of the String class and returns a new string based on specified indices.

Two Variants of substring()

  • substring(int beginIndex): Returns a substring starting from beginIndex (inclusive) to the end of the string.

    • Example: "Hello, World!".substring(7) returns "World!".

  • substring(int beginIndex, int endIndex): Returns a substring from beginIndex (inclusive) to endIndex (exclusive).

    • Example: "Hello, World!".substring(0, 5) returns "Hello".

Key Points

  • Indices start at 0.

  • The endIndex is exclusive, meaning the character at that index is not included.

  • The method does not modify the original string—strings are immutable in Java.

  • Throws StringIndexOutOfBoundsException if indices are invalid (e.g., negative, greater than length, or beginIndex > endIndex).

Common Use Cases

  • Extracting file extensions: filename.substring(filename.lastIndexOf(".") + 1).

  • Parsing dates: date.substring(0, 4) for the year.

  • Removing first/last characters: str.substring(1) removes the first character; str.substring(0, str.length() - 1) removes the last.

Always validate indices before calling substring() to avoid runtime exceptions.

🌐
W3Schools
w3schools.com › java › ref_string_substring.asp
Java String substring() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... The substring() method returns a substring from the string.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
October 20, 2025 - The class String includes methods ... for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class. The Java language provides ...
Discussions

Java - Strings and the substring method - Stack Overflow
I have some question that I wonder about. I know that string are immutable in Java and therefore a new string object is created rather than changed when for example assigning to a existing string o... More on stackoverflow.com
🌐 stackoverflow.com
How to correctly use the substring method? (Java)
You are deeply confused about how substring() works - it's a method of String, and it does not take Strings as parameters. See here for an example. More on reddit.com
🌐 r/learnprogramming
5
5
February 2, 2013
java - how the subString() function of string class works - Stack Overflow
As pointed out by Pete Kirkham, this is implementation specific. My answer is only correct for the Sun JRE, and only prior to Java 7 update 6. You're right about a normal substring call just creating a new string referring to the same character array as the original string. More on stackoverflow.com
🌐 stackoverflow.com
[JAVA] Substring method question about indexing.
Index 0 does refer to R. The range of the substring method is [beginIndex, endIndex). So what you have says to start at the beginning, then include only things before the first character, which is nothing, so you get an empty string. If you want just the first character you need substring(0, 1). It may be easier to think of if you consider the parameters to be beginIndex and beginIndex + substringLength. More on reddit.com
🌐 r/learnprogramming
2
1
July 6, 2012
🌐
GeeksforGeeks
geeksforgeeks.org › java › substring-in-java
Java String substring() Method - GeeksforGeeks
April 11, 2025 - In Java, the substring() method of the String class returns a substring from the given string.
🌐
Career Karma
careerkarma.com › blog › java › java substring: a how-to guide
Java Substring: A How-To Guide | Career Karma
December 1, 2023 - The Java substring() method returns a portion of a particular string. This method accepts the start and end index values of the characters you would like to retrieve from a string.
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-substring-method-example
Java String substring() Method with examples
Note: The method is called like this: substring(start + 1, end), here start index is +1 because, we want to get the substring after the delimiter position, however the end index is not +1 because end index is not inclusive in substring method. public class JavaExample{ public static void main(String[] args){ //given string String str = "Welcome to [BeginnersBook.com]"; //we would like to get the substring between '[' and ']' int start = str.indexOf("["); int end = str.indexOf("]"); String outStr = str.substring(start + 1, end); System.out.println(outStr); } }
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.string.substring
String.Substring Method (Java.Lang) | Microsoft Learn
Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
🌐
Simplilearn
simplilearn.com › home › resources › software development › all you should know about substring in java
All You Should Know About Substring in Java | Simplilearn
September 11, 2025 - A substring is a part of another string. It's a commonly used method in java. Explore this tutorial to get an in-depth idea about substring in java. Start now!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
Find elsewhere
🌐
FavTutor
favtutor.com › blogs › java-substrings
Substring in Java (with examples)
November 5, 2023 - In Java, the substring is a powerful method that allows developers to extract subsets or parts of a string. By using the substring() method, you can create smaller strings from a bigger one without modifying the original string.
🌐
OpenJDK
openjdk.org › jeps › 8303099
JEP draft: Null-Restricted and Nullable Types (Preview)
February 23, 2023 - In a Java program, a variable of type String may hold either a reference to a String object or the special value null. In some cases, the author intends that the variable will always hold a reference to a String object; in other cases, the author expects null as a meaningful value.
🌐
Oracle
docs.oracle.com › javase › tutorial › java › data › manipstrings.html
Manipulating Characters in a String (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)
As shown in the following figure, our extension method uses lastIndexOf to locate the last occurrence of the period (.) in the file name. Then substring uses the return value of lastIndexOf to extract the file name extension — that is, the substring from the period to the end of the string.
Top answer
1 of 2
9

Strings in Java are immutable. Basically this means that, once you create a string object, you won't be able to modify/change the content of a string. As a result, if you perform any manipulation on a string object which "appears to" change the content of the string, Java creates a new string object, and performs the manipulation on the newly created one.

Based on this, your code above appears to create five string objects - two are created by the declaration, two are created by calls to substring, and the last one is created after you concatenate the two pieces.

Immutability however leads to another interesting consequence. JVM internally maintains something like a string pool for creating string literals. For saving up memory, JVM will try to use string objects from this pool. Whenever you create a new string literal, JVM will loop into the pool to see if any existing strings can be used. If there is, JVM will simply use it and return it.

So, technically, before Java 7, JVM will create only one string object for your whole code. Even your substring calls won't create new string objects in the pool, it will use the existing "Hello World" one, but in this case it will only use characters from position 0 to 3 for your first call to substring, for example. Starting from Java 7, substring will not share the characters, but will create a new one. So, total object count will be 4 - the last one will be created with the concatenation of the two substrings.

Edit To answer your question in the comment, take a look at Java Language Specification -

In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).

A String object is immutable, that is, its contents never change, while an array of char has mutable elements.

The method toCharArray in class String returns an array of characters containing the same character sequence as a String. The class StringBuffer implements useful methods on mutable arrays of characters.

So, no, char arrays are not immutable in Java, they are mutable.

2 of 2
0

Literal a is created newly and kept in the pool.Literal b refer the a, it will not create new one instead.

The line 3 will create 3 new String since substring creates a new string and concatenate creates new Strings every time.

String substring(int beginIndex,int endIndex)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

🌐
IronPDF
ironpdf.com › ironpdf for java › ironpdf for java blog › java help › java substring method
Java Substring Method (How It Works For Developers)
November 18, 2025 - Java offers two main ways to do this: public String substring(int beginIndex): This method creates a new string starting from the beginIndex to the end of the original string.
🌐
CodingBat
codingbat.com › doc › java-string-substring.html
Java Substring v2
There is a more complex version of substring() that takes both start and end index numbers: substring(int start, int end) returns a string of the chars beginning at the start index number and running up to but not including the end index.
🌐
Reddit
reddit.com › r/learnprogramming › how to correctly use the substring method? (java)
r/learnprogramming on Reddit: How to correctly use the substring method? (Java)
February 2, 2013 -

Hey guys, I've been working on this Java homework for my class and this whole section about string manipulation is confusing me.

The homework asks to add statements that use the substring method to get the first half and second half of phrase.

I'm assuming that means using the substring method, but I always get errors trying to compile what I put in. So here's the code. I'm not exactly sure how to use the substring method in the way they ask, and my book doesn't really go over it well. Should I be creating another variable or just use what I have?

🌐
Tutorialspoint
tutorialspoint.com › home › java/lang › java string substring
Java String Substring
September 1, 2008 - Learn how to use the substring() method in Java to extract parts of a string effectively.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › lang › String.html
String (Java SE 11 & JDK 11 )
January 20, 2026 - A substring of this String object is compared to a substring of the argument other. The result is true if these substrings represent identical character sequences. The substring of this String object to be compared begins at index toffset and has length len. The substring of other to be compared ...
Top answer
1 of 7
9

As pointed out by Pete Kirkham, this is implementation specific. My answer is only correct for the Sun JRE, and only prior to Java 7 update 6.

You're right about a normal substring call just creating a new string referring to the same character array as the original string. That's what happens on line 5 too. The fact that the new string object reference happens to be assigned to a variable doesn't change the behaviour of the method.

Just to be clear, you say that in line 2 the new string will still point to "Monday" - the char array reference inside the string will be to the same char array as one used for "Monday". But "Monday" is a string in itself, not a char array. In other words, by the time line 2 has finished (and ignoring GC) there are two string objects, both referring to the same char array. One has a count of 6 and the other has a count of 3; both have an offset of 0.

You're wrong about line 4 using a "string pool" though - there's no pooling going on there. However, it is different to the other lines. When you call the String(String) constructor, the new string takes a copy of the character data of the original, so it's completely separate. This can be very useful if you only need a string which contains a small part of a very large original string; it allows the original large char array to be garbage collected (assuming nothing else needs it) while you hold onto the copy of the small portion. A good example of this in my own experience is reading lines from a line. By default, BufferedLineReader will read lines using an 80-character buffer, so every string returned will use a char array of at least 80 characters. If you're reading lots of very short lines (single words) the difference in terms of memory consumption just through the use of the odd-looking

line = new String(line);

can be very significant.

Does that help?

2 of 7
7

I know that line 2 will still point to "Monday" and have a new String object with the offset and count set to 0,3.

That is currently true of the Sun JRE implementation. I seem to recall that was not true of the Sun implementation in the past, and is not true of other implementations of the JVM. Do not rely on behaviour which is not specified. GNU classpath might copy the array (I can't remember off hand what ratio is uses to decide when to copy, but it does copy if the copy is a small enough fraction of the original, which turned one nice O(N) algorithm to O(N^2)).

The line 4 will create a new String "Mon" in string pool and point to it.

No, it creates a new string object in the heap, subject to the same garbage collection rules as any other object. Whether or not it shares the same underlying character array is implementation dependant. Do not rely on behaviour which is not specified.

The String(String) constructor says:

Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

The String(char[]) constructor says:

Allocates a new String so that it represents the sequence of characters currently contained in the character array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.

Following good OO principles, no method of String actually requires that it is implemented using a character array, so no part of the specification of String requires operations on an character array. Those operations which take an array as input specify that the contents of the array are copied to whatever internal storage is used in the String. A string could use UTF-8 or LZ compression internally and conform to the API.

However, if your JVM doesn't make the small-ratio sub-string optimisation, then there's a chance that it does copy only the relevant portion when you use new String(String), so it's a case of trying it a seeing if it improves the memory use. Not everything which effects Java runtimes is defined by Java.

To obtain a string in the string pool which is equal to a string, use the intern() method. This will either retrieve a string from the pool if one with the value already has been interned, or create a new string and put it in the pool. Note that pooled strings have different (again implementation dependent) garbage collection behaviour.

🌐
Coderanch
coderanch.com › t › 497744 › java › Implementing-substring-method
Implementing substring method in my own way. (Beginning Java forum at Coderanch)
June 2, 2010 - Gopi Chand Maddula wrote:I am trying to code the functionality of substring method of String Class My intention is to substring the given string without using any predefined methods. I'm pretty sure that's impossible. Maybe you mean "without using any predefined methods other than toCharArray()".
🌐
The Renegade Coder
therenegadecoder.com › code › be-careful-with-strings-substring-method-in-java
Be Careful with String’s Substring Method in Java – The Renegade Coder
May 26, 2020 - Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. Java API, 2019