How does Integer.toString() works internally?

I found that a similar question has been asked before here : how does Float.toString() and Integer.toString() works?

But this doesn’t speak about how that function internally works. When I opened the internally source code of Integer.toString(), it is not understandable for normal junior java programmer.

Can somebody please explain what happens internally in short description ?


NOTE : This was one of the interview questions that I was asked recently. I had no idea about how to answer such question !

Answer

The no arg call of integer.toString() simply calls the static method Integer.toString(int i) (using the integer variables own primitive value), which is implemented as below;

  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);
   }

First it checks whether it’s value is == the lowest possible integer, and returns that if it is equal. If not, then it checks what size the String needs to be using the stringSize() method of Integer to use as the size of an array of characters.

stringSize() implementation below;

  static int stringSize(int x) {
       for (int i=0; ; i++)
           if (x <= sizeTable[i])
               return i+1;
   }

Once it has a char[] of the correct size, it then populates that array using the getChars() method, implemented below;

  static void getChars(int i, int index, char[] buf) {
       int q, r;
       int charPos = index;
       char sign = 0;

       if (i < 0) {
           sign = '-';
           i = -i;
       }

       // Generate two digits per iteration
       while (i >= 65536) {
           q = i / 100;
       // really: r = i - (q * 100);
           r = i - ((q << 6) + (q << 5) + (q << 2));
           i = q;
           buf [--charPos] = DigitOnes[r];
           buf [--charPos] = DigitTens[r];
       }

       // Fall thru to fast mode for smaller numbers
       // assert(i <= 65536, i);
       for (;;) {
           q = (i * 52429) >>> (16+3);
           r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
           buf [--charPos] = digits [r];
           i = q;
           if (i == 0) break;
       }
       if (sign != 0) {
           buf [--charPos] = sign;
       }
   }

Explaining each individual step would take far too long for for a stackoverflow answer. The most pertinent section however (as pointed out in the comments) is the getChars() method which, complicated bit shifting aside, is essentially process of elimination for finding each character. I am afraid I can’t go into any greater detail than that without going beyond my own understanding.

Leave a Reply

Your email address will not be published. Required fields are marked *