I always thought if I do String s = "Hello World".substring(0, 5)
, then I just get a new string s = "Hello"
. This is also documented in the Java API doc: "Returns a new string that is a substring of this string".
But when I saw the following two links, I began to doubt.
What is the purpose of the expression "new String(...)" in Java?
String constructor considered useless turns out to be useful after all
Basically, they say if I use String s = "Hello World".subString(0, 5)
, I still get a String which holds "Hello World"'s char array.
Why? Does Java really implement substring in this way? Why in this way? Why not just return a brand new shorter substring?
The substring(int beginIndex, int endIndex) method of the String class. It 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.
The substring() method returns a substring of the given string. This is a built-in method of string class that can be called by a string, it returns the substring based on the index values passed to this method. For example: “Beginnersbook”. substring(9) would return “book” as a substring.
1. String substring(): This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. Endindex of substring starts from 1 and not from 0.
The difference between substring() and substr() The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .
Turning it around, why allocate a new char[]
when it is not necessary? This is a valid implementation since String
is immutable. It saves allocations and memory in the aggregate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With