Fiona
Fiona

Reputation: 57

question about the length of strings in java

I got a question about the Strings in Java:

new String(array, 0, end)

here, I don't know why we use 'end' instead of end-1? I mean, the array I want to store(0, end - 1).

Upvotes: 2

Views: 78

Answers (2)

WJS
WJS

Reputation: 40024

Although you misunderstood the use of the count feature, your question does raise a feature that is common throughout Java and other languages as well. Most ranges go from a to b where a is inclusive and b is exclusive.

The following example, albeit contrived, shows how this can help.

String.substring() is one such example:

Notice subsequent calls of substring use the previous ending index as the start of the next. This makes it easy to think about concatentating strings.

      String str = "encyclopedia";
      String newstr1 =
            str.substring(0, 3) + str.substring(3, 6) + str.substring(6);
      String newstr2 =
            str.substring(0, 2) + str.substring(2, 4) + str.substring(4);

      System.out.println(str);
      System.out.println(newstr1);
      System.out.println(newstr2);

All three print statement print encyclopedia

Upvotes: 0

Sunil Dabburi
Sunil Dabburi

Reputation: 1472

If you look inside String.java, you could see that the third parameter is count

public String(char value[], int offset, int count)

value[] - input char array
offset - from which position you want the chars to be copied
count - number of chars to copy

So if you have a char[] of size 10, you could create a string as follows

new String(input, 0, 10); // NOT new String(input, 0, 9);

Upvotes: 1

Related Questions