🌐
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 ...
🌐
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.
Discussions

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 new to learning - Stack Overflow
Im new to java and understand substring pretty well. Im confused to what the str.substring(i,i +3) means. the i is the index of what? More on stackoverflow.com
🌐 stackoverflow.com
The String.substring() in java - Stack Overflow
No, it’s OK to begin the substring at the end of the string, it just gives you the empty string, "" (the string has length 0). ... Check the Javadoc. ... The documentation says “Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.” ... 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
🌐
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 ...
🌐
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.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.string.substring
String.Substring Method (Java.Lang) | Microsoft Learn
"hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile" </blockquote> Java documentation for java.lang.String.substring(int, int).
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › lang › String.html
String (Java SE 17 & JDK 17)
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 ...
🌐
Codecademy
codecademy.com › docs › java › strings › .substring()
Java | Strings | .substring() | Codecademy
April 28, 2025 - The .substring() method in Java returns a portion of a string from a specified starting index to an (optional) ending index.
Find elsewhere
🌐
Java Almanac
javaalmanac.io › jdk › 1.2 › api › java › lang › String.html
Java Platform 1.2 API Specification: Class String
A substring of this String object is compared to a substring of the argument other. The result is true if these substrings represent character sequences that are the same, ignoring case if and only if ignoreCase is true. The substring of this String object to be compared begins at index toffset ...
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › substring
Java String substring() - Extract Substring | Vultr Docs
January 1, 2025 - Looping over a string to extract multiple substrings is a common use case, for example, parsing a formatted data string: Consider a scenario where you want to extract words separately from a string containing space-separated words: ... String sentence = "Java substring method"; String[] words = sentence.split(" "); for(String word : words) { System.out.println(word); } Explain Code
🌐
Android Developers
developer.android.com › api reference › string
String | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
W3Schools
w3schools.com › java › java_ref_string.asp
Java String Reference
assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String Methods · charAt() codePointAt() codePointBefore() codePointCount() compareTo() compareToIgnoreCase() concat() contains() contentEquals() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() isEmpty() join() lastIndexOf() length() matches() offsetByCodePoints() regionMatches() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toCharArray() toLowerCase() toString() toUpperCase() trim() valueOf() Java Math Methods ·
🌐
How to do in Java
howtodoinjava.com › home › string › java string substring()
Java String substring() with Examples - HowToDoInJava
January 10, 2023 - ... The following is a pictorial representation of the array in memory. 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.
🌐
Oracle
docs.oracle.com › en › java › javase › 22 › docs › api › java.base › java › lang › String.html
String (Java SE 22 & JDK 22)
July 16, 2024 - 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.

Top answer
1 of 2
1

For example. In the following string we have 6 characters. So if you call .length() on the string it will return 6. Note that its indices will range from 0 to 5 (not to 6).

"A tree"

The indices would be like the following:

0 -> 'A'
1 -> ' '
2 -> 't'
3 -> 'r'
4 -> 'e'
5 -> 'e'

Using substring you can get a part of this string. Your result will be starting at the specifed begin index and will end at the specified end index.

Important:

The start index is inclusive, while the end index is exclusive.

Which means that if we use substring from 2 to 4, we won't get "tre". We will get "tr", since the end index is not included.


Programmers often use excluded end indices, since it is easier to work with them. For example. Imagine our string "A tree" is called s like this:

String s = "A tree";

if you would want everything starting at index 2 you could do:

String result = s.substring(2, s.length()); // Result would also be 'tree' for this example

If the end index wouldn't be exclusive you would need to write:

String result = s.substring(2, s.length() - 1); // This is an example that would return "tree", IF and only if end indices wouldn't be excluded

That is why programmers often exclude the end index.

Of corse if you want to start at a certain index and want to go till the end you don't need to use

String result = s.substring(2, s.length()); // Result would also be 'tree' for this example

but instead you could use the alternative version of substring, where you only provide a begin index and not an end index. Like this:

String result = s.substring(2); // Result would also be 'tree' for this example

Please take a look at the documentation for

  1. substring(int, int) -> https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring-int-int-
  2. substring(int) -> https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring-int-
2 of 2
0
String text = "abcxyz";

The substring is on a loop so at the first pass text will be equal to :

System.out.println(text.substring(0, 0 + 3)); // abc

At the second pass :

System.out.println(text.substring(1, 1 + 3)); // bcx

Etc.

🌐
GeeksforGeeks
geeksforgeeks.org › java › string-class-in-java
String Class in Java - GeeksforGeeks
November 12, 2025 - The String class in Java is used to create and manipulate sequences of characters. It is one of the most commonly used classes in Java.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.string
String Class (Java.Lang) | Microsoft Learn
All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: <blockquote> ... System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2,3); String d = cde.substring(1, 2);
🌐
Cornell Computer Science
cs.cornell.edu › courses › JavaAndDS › apiString › API13String.pdf pdf
Java API spec for class String
Click on the link JavaHyperText ... being a Java or data-structure entry. Use the Filter Field on that page to look for entries of interest to you at the moment. Each entry contains text, perhaps links to pdf files, and perhaps links to webpages with videos to watch. We call it a HyperText because: (1) it is a text, an online text, and (2) it is indeed hypertext, that is, it is an electronic document with each ...
🌐
Coderanch
coderanch.com › t › 709869 › java › Substrings
Substrings (Beginning Java forum at Coderanch)
May 16, 2019 - The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string. This method extracts the characters in a string between "start" and "end", not including "end" itself. So, when you do something like it starts counting from 0 till 4 ...