Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does String.substring exactly do in Java?

Tags:

java

string

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?

like image 840
Jackson Tale Avatar asked May 31 '12 08:05

Jackson Tale


People also ask

How does substring () inside string works?

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.

What is the purpose of the substring () method and how do you use it?

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.

What does substring 1 do in Java?

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.

What substring () and substr () will do?

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 .


1 Answers

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.

like image 142
Sean Owen Avatar answered Oct 23 '22 11:10

Sean Owen