Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the constructor String(int, int, char[]) defined?

I am trying to understand the implementation of Integer.toString(), which looks like this:

public static String toString(int i) {
    if (i == Integer.MIN_VALUE)
        return "-2147483648";
    int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    char[] buf = new char[size];
    getChars(i, size, buf);
    return new String(0, size, buf);
}

And I ran into the last line, which doesn't look like any of the constructors in the String class, except this one:

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

...except that this function is called with the char[] argument first, unlike how it is being used in Integer.toString(). I was under the impression that changing the order of arguments counted as a change in the signature of the method, and would be a different overwrite of the method.

Why does this work, or am I interpreting this incorrectly?

like image 219
efong5 Avatar asked Aug 05 '17 01:08

efong5


People also ask

What is string in constructor?

The String(Char[]) constructor copies all the characters in the array to the new string. The String(Char[], Int32, Int32) constructor copies the characters from index startIndex to index startIndex + length - 1 to the new string. If length is zero, the value of the new string is String. Empty.

How do you define a constructor in Java?

Constructor(s) of a class must have the same name as the class name in which it resides. A constructor in Java can not be abstract, final, static, or Synchronized. Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

How do you call a string constructor in Java?

1. String(): To create an empty String, we will call the default constructor. The general syntax to create an empty string in java program is as follows: String s = new String();

How many constructors are there in String class?

The String class has over 60 methods and 13 constructors.


1 Answers

That's using a package-private String constructor. It doesn't show up in the String Javadoc, because it's package-private.

If you check the String source code on the same site, you'll see

  644       // Package private constructor which shares value array for speed.
  645       String(int offset, int count, char value[]) {
  646           this.value = value;
  647           this.offset = offset;
  648           this.count = count;
  649       }
like image 169
user2357112 supports Monica Avatar answered Oct 19 '22 04:10

user2357112 supports Monica