src/share/classes/java/lang/Long.java

Print this page
rev 10062 : 8041972: Add improved parse/format methods for Long/Integer
Contributed-by: redestad


   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.annotation.Native;

  29 import java.math.*;
  30 
  31 
  32 /**
  33  * The {@code Long} class wraps a value of the primitive type {@code
  34  * long} in an object. An object of type {@code Long} contains a
  35  * single field whose type is {@code long}.
  36  *
  37  * <p> In addition, this class provides several methods for converting
  38  * a {@code long} to a {@code String} and a {@code String} to a {@code
  39  * long}, as well as other constants and methods useful when dealing
  40  * with a {@code long}.
  41  *
  42  * <p>Implementation note: The implementations of the "bit twiddling"
  43  * methods (such as {@link #highestOneBit(long) highestOneBit} and
  44  * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
  45  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
  46  * Delight</i>, (Addison Wesley, 2002).
  47  *
  48  * @author  Lee Boynton


 529      * parseLong("0", 10) returns 0L
 530      * parseLong("473", 10) returns 473L
 531      * parseLong("+42", 10) returns 42L
 532      * parseLong("-0", 10) returns 0L
 533      * parseLong("-FF", 16) returns -255L
 534      * parseLong("1100110", 2) returns 102L
 535      * parseLong("99", 8) throws a NumberFormatException
 536      * parseLong("Hazelnut", 10) throws a NumberFormatException
 537      * parseLong("Hazelnut", 36) returns 1356099454469L
 538      * </pre></blockquote>
 539      *
 540      * @param      s       the {@code String} containing the
 541      *                     {@code long} representation to be parsed.
 542      * @param      radix   the radix to be used while parsing {@code s}.
 543      * @return     the {@code long} represented by the string argument in
 544      *             the specified radix.
 545      * @throws     NumberFormatException  if the string does not contain a
 546      *             parsable {@code long}.
 547      */
 548     public static long parseLong(String s, int radix)
 549               throws NumberFormatException
 550     {
 551         if (s == null) {
 552             throw new NumberFormatException("null");






























 553         }
 554 


































 555         if (radix < Character.MIN_RADIX) {
 556             throw new NumberFormatException("radix " + radix +
 557                                             " less than Character.MIN_RADIX");
 558         }
 559         if (radix > Character.MAX_RADIX) {
 560             throw new NumberFormatException("radix " + radix +
 561                                             " greater than Character.MAX_RADIX");
 562         }
 563 
 564         long result = 0;
 565         boolean negative = false;
 566         int i = 0, len = s.length();
 567         long limit = -Long.MAX_VALUE;
 568         long multmin;
 569         int digit;
 570 
 571         if (len > 0) {
 572             char firstChar = s.charAt(0);
 573             if (firstChar < '0') { // Possible leading "+" or "-"
 574                 if (firstChar == '-') {
 575                     negative = true;
 576                     limit = Long.MIN_VALUE;
 577                 } else if (firstChar != '+')
 578                     throw NumberFormatException.forInputString(s);
 579 
 580                 if (len == 1) // Cannot have lone "+" or "-"
 581                     throw NumberFormatException.forInputString(s);
 582                 i++;



 583             }
 584             multmin = limit / radix;
 585             while (i < len) {
 586                 // Accumulating negatively avoids surprises near MAX_VALUE
 587                 digit = Character.digit(s.charAt(i++),radix);
 588                 if (digit < 0) {
 589                     throw NumberFormatException.forInputString(s);
 590                 }
 591                 if (result < multmin) {
 592                     throw NumberFormatException.forInputString(s);
 593                 }
 594                 result *= radix;
 595                 if (result < limit + digit) {
 596                     throw NumberFormatException.forInputString(s);
 597                 }
 598                 result -= digit;
 599             }
 600         } else {
 601             throw NumberFormatException.forInputString(s);
 602         }
 603         return negative ? result : -result;
 604     }
 605 
 606     /**
 607      * Parses the string argument as a signed decimal {@code long}.
 608      * The characters in the string must all be decimal digits, except
 609      * that the first character may be an ASCII minus sign {@code '-'}
 610      * ({@code \u005Cu002D'}) to indicate a negative value or an
 611      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
 612      * indicate a positive value. The resulting {@code long} value is
 613      * returned, exactly as if the argument and the radix {@code 10}
 614      * were given as arguments to the {@link
 615      * #parseLong(java.lang.String, int)} method.
 616      *
 617      * <p>Note that neither the character {@code L}
 618      * ({@code '\u005Cu004C'}) nor {@code l}
 619      * ({@code '\u005Cu006C'}) is permitted to appear at the end
 620      * of the string as a type indicator, as would be permitted in
 621      * Java programming language source code.
 622      *
 623      * @param      s   a {@code String} containing the {@code long}
 624      *             representation to be parsed
 625      * @return     the {@code long} represented by the argument in
 626      *             decimal.
 627      * @throws     NumberFormatException  if the string does not contain a
 628      *             parsable {@code long}.
 629      */
 630     public static long parseLong(String s) throws NumberFormatException {
 631         return parseLong(s, 10);

 632     }
 633 
 634     /**
 635      * Parses the string argument as an unsigned {@code long} in the
 636      * radix specified by the second argument.  An unsigned integer
 637      * maps the values usually associated with negative numbers to
 638      * positive numbers larger than {@code MAX_VALUE}.
 639      *
 640      * The characters in the string must all be digits of the
 641      * specified radix (as determined by whether {@link
 642      * java.lang.Character#digit(char, int)} returns a nonnegative
 643      * value), except that the first character may be an ASCII plus
 644      * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
 645      * integer value is returned.
 646      *
 647      * <p>An exception of type {@code NumberFormatException} is
 648      * thrown if any of the following situations occurs:
 649      * <ul>
 650      * <li>The first argument is {@code null} or is a string of
 651      * length zero.


 659      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 660      * string is longer than length 1.
 661      *
 662      * <li>The value represented by the string is larger than the
 663      * largest unsigned {@code long}, 2<sup>64</sup>-1.
 664      *
 665      * </ul>
 666      *
 667      *
 668      * @param      s   the {@code String} containing the unsigned integer
 669      *                  representation to be parsed
 670      * @param      radix   the radix to be used while parsing {@code s}.
 671      * @return     the unsigned {@code long} represented by the string
 672      *             argument in the specified radix.
 673      * @throws     NumberFormatException if the {@code String}
 674      *             does not contain a parsable {@code long}.
 675      * @since 1.8
 676      */
 677     public static long parseUnsignedLong(String s, int radix)
 678                 throws NumberFormatException {
 679         if (s == null)  {
 680             throw new NumberFormatException("null");































 681         }
 682 
 683         int len = s.length();


































 684         if (len > 0) {
 685             char firstChar = s.charAt(0);
 686             if (firstChar == '-') {
 687                 throw new
 688                     NumberFormatException(String.format("Illegal leading minus sign " +
 689                                                        "on unsigned string %s.", s));
 690             } else {
 691                 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits
 692                     (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits
 693                     return parseLong(s, radix);
 694                 }
 695 
 696                 // No need for range checks on len due to testing above.
 697                 long first = parseLong(s.substring(0, len - 1), radix);
 698                 int second = Character.digit(s.charAt(len - 1), radix);
 699                 if (second < 0) {
 700                     throw new NumberFormatException("Bad digit at end of " + s);

 701                 }
 702                 long result = first * radix + second;
 703 
 704                 /*
 705                  * Test leftmost bits of multiprecision extension of first*radix
 706                  * for overflow. The number of bits needed is defined by
 707                  * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then
 708                  * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and
 709                  * overflow is tested by splitting guard in the ranges
 710                  * guard < 92, 92 <= guard < 128, and 128 <= guard, where
 711                  * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take
 712                  * on a value which does not include a prime factor in the legal
 713                  * radix range.
 714                  */
 715                 int guard = radix * (int) (first >>> 57);
 716                 if (guard >= 128 ||
 717                     (result >= 0 && guard >= 128 - Character.MAX_RADIX)) {
 718                     /*
 719                      * For purposes of exposition, the programmatic statements
 720                      * below should be taken to be multi-precision, i.e., not


 737                      * so that first*radix + second >= 92*2^57 + 0 > 2^63
 738                      *
 739                      * D) Condition guard < 128:
 740                      * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1)
 741                      * so
 742                      * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36
 743                      * thus
 744                      * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36
 745                      * whence
 746                      * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63
 747                      *
 748                      * E) Conditions C, D, and result >= 0:
 749                      * C and D combined imply the mathematical result
 750                      * 2^63 < first*radix + second < 2^64 + 2^63. The lower
 751                      * bound is therefore negative as a signed long, but the
 752                      * upper bound is too small to overflow again after the
 753                      * signed long overflows to positive above 2^64 - 1. Hence
 754                      * result >= 0 implies overflow given C and D.
 755                      */
 756                     throw new NumberFormatException(String.format("String value %s exceeds " +
 757                                                                   "range of unsigned long.", s));
 758                 }
 759                 return result;
 760             }
 761         } else {
 762             throw NumberFormatException.forInputString(s);
 763         }
 764     }
 765 
 766     /**
 767      * Parses the string argument as an unsigned decimal {@code long}. The
 768      * characters in the string must all be decimal digits, except
 769      * that the first character may be an an ASCII plus sign {@code
 770      * '+'} ({@code '\u005Cu002B'}). The resulting integer value
 771      * is returned, exactly as if the argument and the radix 10 were
 772      * given as arguments to the {@link
 773      * #parseUnsignedLong(java.lang.String, int)} method.
 774      *
 775      * @param s   a {@code String} containing the unsigned {@code long}
 776      *            representation to be parsed
 777      * @return    the unsigned {@code long} value represented by the decimal string argument
 778      * @throws    NumberFormatException  if the string does not contain a
 779      *            parsable unsigned integer.
 780      * @since 1.8
 781      */
 782     public static long parseUnsignedLong(String s) throws NumberFormatException {
 783         return parseUnsignedLong(s, 10);

 784     }
 785 
 786     /**
 787      * Returns a {@code Long} object holding the value
 788      * extracted from the specified {@code String} when parsed
 789      * with the radix given by the second argument.  The first
 790      * argument is interpreted as representing a signed
 791      * {@code long} in the radix specified by the second
 792      * argument, exactly as if the arguments were given to the {@link
 793      * #parseLong(java.lang.String, int)} method. The result is a
 794      * {@code Long} object that represents the {@code long}
 795      * value specified by the string.
 796      *
 797      * <p>In other words, this method returns a {@code Long} object equal
 798      * to the value of:
 799      *
 800      * <blockquote>
 801      *  {@code new Long(Long.parseLong(s, radix))}
 802      * </blockquote>
 803      *
 804      * @param      s       the string to be parsed
 805      * @param      radix   the radix to be used in interpreting {@code s}
 806      * @return     a {@code Long} object holding the value
 807      *             represented by the string argument in the specified
 808      *             radix.
 809      * @throws     NumberFormatException  If the {@code String} does not
 810      *             contain a parsable {@code long}.
 811      */
 812     public static Long valueOf(String s, int radix) throws NumberFormatException {
 813         return Long.valueOf(parseLong(s, radix));

 814     }
 815 
 816     /**
 817      * Returns a {@code Long} object holding the value
 818      * of the specified {@code String}. The argument is
 819      * interpreted as representing a signed decimal {@code long},
 820      * exactly as if the argument were given to the {@link
 821      * #parseLong(java.lang.String)} method. The result is a
 822      * {@code Long} object that represents the integer value
 823      * specified by the string.
 824      *
 825      * <p>In other words, this method returns a {@code Long} object
 826      * equal to the value of:
 827      *
 828      * <blockquote>
 829      *  {@code new Long(Long.parseLong(s))}
 830      * </blockquote>
 831      *
 832      * @param      s   the string to be parsed.
 833      * @return     a {@code Long} object holding the value
 834      *             represented by the string argument.
 835      * @throws     NumberFormatException  If the string cannot be parsed
 836      *             as a {@code long}.
 837      */
 838     public static Long valueOf(String s) throws NumberFormatException
 839     {
 840         return Long.valueOf(parseLong(s, 10));
 841     }
 842 
 843     private static class LongCache {
 844         private LongCache(){}
 845 
 846         static final Long cache[] = new Long[-(-128) + 127 + 1];
 847 
 848         static {
 849             for(int i = 0; i < cache.length; i++)
 850                 cache[i] = new Long(i - 128);
 851         }
 852     }
 853 
 854     /**
 855      * Returns a {@code Long} instance representing the specified
 856      * {@code long} value.
 857      * If a new {@code Long} instance is not required, this method
 858      * should generally be used in preference to the constructor
 859      * {@link #Long(long)}, as this method is likely to yield
 860      * significantly better space and time performance by caching


 982      *          {@code Long} object.
 983      */
 984     public Long(long value) {
 985         this.value = value;
 986     }
 987 
 988     /**
 989      * Constructs a newly allocated {@code Long} object that
 990      * represents the {@code long} value indicated by the
 991      * {@code String} parameter. The string is converted to a
 992      * {@code long} value in exactly the manner used by the
 993      * {@code parseLong} method for radix 10.
 994      *
 995      * @param      s   the {@code String} to be converted to a
 996      *             {@code Long}.
 997      * @throws     NumberFormatException  if the {@code String} does not
 998      *             contain a parsable {@code long}.
 999      * @see        java.lang.Long#parseLong(java.lang.String, int)
1000      */
1001     public Long(String s) throws NumberFormatException {
1002         this.value = parseLong(s, 10);

1003     }
1004 
1005     /**
1006      * Returns the value of this {@code Long} as a {@code byte} after
1007      * a narrowing primitive conversion.
1008      * @jls 5.1.3 Narrowing Primitive Conversions
1009      */
1010     public byte byteValue() {
1011         return (byte)value;
1012     }
1013 
1014     /**
1015      * Returns the value of this {@code Long} as a {@code short} after
1016      * a narrowing primitive conversion.
1017      * @jls 5.1.3 Narrowing Primitive Conversions
1018      */
1019     public short shortValue() {
1020         return (short)value;
1021     }
1022 




   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.annotation.Native;
  29 import static java.lang.Integer.requireNonEmpty;
  30 import java.math.*;
  31 
  32 
  33 /**
  34  * The {@code Long} class wraps a value of the primitive type {@code
  35  * long} in an object. An object of type {@code Long} contains a
  36  * single field whose type is {@code long}.
  37  *
  38  * <p> In addition, this class provides several methods for converting
  39  * a {@code long} to a {@code String} and a {@code String} to a {@code
  40  * long}, as well as other constants and methods useful when dealing
  41  * with a {@code long}.
  42  *
  43  * <p>Implementation note: The implementations of the "bit twiddling"
  44  * methods (such as {@link #highestOneBit(long) highestOneBit} and
  45  * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
  46  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
  47  * Delight</i>, (Addison Wesley, 2002).
  48  *
  49  * @author  Lee Boynton


 530      * parseLong("0", 10) returns 0L
 531      * parseLong("473", 10) returns 473L
 532      * parseLong("+42", 10) returns 42L
 533      * parseLong("-0", 10) returns 0L
 534      * parseLong("-FF", 16) returns -255L
 535      * parseLong("1100110", 2) returns 102L
 536      * parseLong("99", 8) throws a NumberFormatException
 537      * parseLong("Hazelnut", 10) throws a NumberFormatException
 538      * parseLong("Hazelnut", 36) returns 1356099454469L
 539      * </pre></blockquote>
 540      *
 541      * @param      s       the {@code String} containing the
 542      *                     {@code long} representation to be parsed.
 543      * @param      radix   the radix to be used while parsing {@code s}.
 544      * @return     the {@code long} represented by the string argument in
 545      *             the specified radix.
 546      * @throws     NumberFormatException  if the string does not contain a
 547      *             parsable {@code long}.
 548      */
 549     public static long parseLong(String s, int radix)
 550               throws NumberFormatException {
 551         requireNonEmpty(s);
 552         return parseLong(s, radix, 0, s.length());
 553     }
 554 
 555     /**
 556      * Parses the {@link CharSequence} argument as a signed {@code long} in
 557      * the specified {@code radix}, beginning at the specified {@code beginIndex}
 558      * and extending to the end of the sequence.
 559      *
 560      * <p>The method does not take steps to guard against the
 561      * {@code CharSequence} being mutated while parsing.
 562      *
 563      * @param      s   the {@code CharSequence} containing the {@code long}
 564      *                  representation to be parsed
 565      * @param      radix   the radix to be used while parsing {@code s}.
 566      * @param      beginIndex   the beginning index, inclusive.
 567      * @return     the signed {@code long} represented by the subsequence in
 568      *             the specified radix.
 569      * @throws     NullPointerException  if {@code s} is null.
 570      * @throws     IllegalArgumentException   if {@code beginIndex} is greater
 571      *             than or equal to {@code s.length()}.
 572      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is negative.
 573      * @throws     NumberFormatException  if the {@code CharSequence} does not
 574      *             contain a parsable {@code long} in the specified
 575      *             {@code radix}, or if {@code radix} is either smaller than
 576      *             {@link java.lang.Character#MIN_RADIX} or larger than
 577      *             {@link java.lang.Character#MAX_RADIX}.
 578      * @since  1.9
 579      */
 580     public static long parseLong(CharSequence s, int radix, int beginIndex)
 581             throws NumberFormatException {
 582         // forces a null check of s
 583         return parseLong(s, radix, beginIndex, s.length());
 584     }
 585 
 586     /**
 587      * Parses the {@link CharSequence} argument as a signed {@code long} in
 588      * the specified {@code radix}, beginning at the specified
 589      * {@code beginIndex} and extending to {@code endIndex - 1}.
 590      *
 591      * <p>The method does not take steps to guard against the
 592      * {@code CharSequence} being mutated while parsing.
 593      *
 594      * @param      s   the {@code CharSequence} containing the {@code long}
 595      *                  representation to be parsed
 596      * @param      radix   the radix to be used while parsing {@code s}.
 597      * @param      beginIndex   the beginning index, inclusive.
 598      * @param      endIndex     the ending index, exclusive.
 599      * @return     the signed {@code long} represented by the subsequence in
 600      *             the specified radix.
 601      * @throws     NullPointerException  if {@code s} is null.
 602      * @throws     IllegalArgumentException   if {@code beginIndex} is greater
 603      *             than or equal to {@code endIndex}.
 604      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is
 605      *             negative, {@code endIndex} is negative or {@code endIndex}
 606      *             is greater than {@code s.length()}
 607      * @throws     NumberFormatException  if the {@code CharSequence} does not
 608      *             contain a parsable {@code long} in the specified
 609      *             {@code radix}, or if {@code radix} is either smaller than
 610      *             {@link java.lang.Character#MIN_RADIX} or larger than
 611      *             {@link java.lang.Character#MAX_RADIX}.
 612      * @since  1.9
 613      */
 614     public static long parseLong(CharSequence s, int radix, int beginIndex, int endIndex)
 615                 throws NumberFormatException {
 616         s.getClass(); // null check
 617         if (beginIndex >= endIndex) {
 618             throw new IllegalArgumentException("beginIndex must be less than endIndex");
 619         }
 620         if (radix < Character.MIN_RADIX) {
 621             throw new NumberFormatException("radix " + radix +
 622                                             " less than Character.MIN_RADIX");
 623         }
 624         if (radix > Character.MAX_RADIX) {
 625             throw new NumberFormatException("radix " + radix +
 626                                             " greater than Character.MAX_RADIX");
 627         }
 628 
 629         long result = 0;
 630         boolean negative = false;
 631         int i = beginIndex, end = endIndex;
 632         long limit = -Long.MAX_VALUE;
 633         long multmin;
 634         int digit;
 635 
 636         char firstChar = s.charAt(i);

 637         if (firstChar < '0') { // Possible leading "+" or "-"
 638             if (firstChar == '-') {
 639                 negative = true;
 640                 limit = Long.MIN_VALUE;
 641             } else if (firstChar != '+') {
 642                 throw NumberFormatException.forInputString(s.toString());
 643             }


 644             i++;
 645             if (end == i) { // Cannot have lone "+" or "-"
 646                 throw NumberFormatException.forInputString(s.toString());
 647             }
 648         }
 649         multmin = limit / radix;
 650         while (i < end) {
 651             // Accumulating negatively avoids surprises near MAX_VALUE
 652             digit = Character.digit(s.charAt(i++), radix);
 653             if (digit < 0 || result < multmin) {
 654                 throw NumberFormatException.forInputString(s.toString());



 655             }
 656             result *= radix;
 657             if (result < limit + digit) {
 658                 throw NumberFormatException.forInputString(s.toString());
 659             }
 660             result -= digit;
 661         }



 662         return negative ? result : -result;
 663     }
 664 
 665     /**
 666      * Parses the string argument as a signed decimal {@code long}.
 667      * The characters in the string must all be decimal digits, except
 668      * that the first character may be an ASCII minus sign {@code '-'}
 669      * ({@code \u005Cu002D'}) to indicate a negative value or an
 670      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
 671      * indicate a positive value. The resulting {@code long} value is
 672      * returned, exactly as if the argument and the radix {@code 10}
 673      * were given as arguments to the {@link
 674      * #parseLong(java.lang.String, int)} method.
 675      *
 676      * <p>Note that neither the character {@code L}
 677      * ({@code '\u005Cu004C'}) nor {@code l}
 678      * ({@code '\u005Cu006C'}) is permitted to appear at the end
 679      * of the string as a type indicator, as would be permitted in
 680      * Java programming language source code.
 681      *
 682      * @param      s   a {@code String} containing the {@code long}
 683      *             representation to be parsed
 684      * @return     the {@code long} represented by the argument in
 685      *             decimal.
 686      * @throws     NumberFormatException  if the string does not contain a
 687      *             parsable {@code long}.
 688      */
 689     public static long parseLong(String s) throws NumberFormatException {
 690         requireNonEmpty(s);
 691         return parseLong(s, 10, 0, s.length());
 692     }
 693 
 694     /**
 695      * Parses the string argument as an unsigned {@code long} in the
 696      * radix specified by the second argument.  An unsigned integer
 697      * maps the values usually associated with negative numbers to
 698      * positive numbers larger than {@code MAX_VALUE}.
 699      *
 700      * The characters in the string must all be digits of the
 701      * specified radix (as determined by whether {@link
 702      * java.lang.Character#digit(char, int)} returns a nonnegative
 703      * value), except that the first character may be an ASCII plus
 704      * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
 705      * integer value is returned.
 706      *
 707      * <p>An exception of type {@code NumberFormatException} is
 708      * thrown if any of the following situations occurs:
 709      * <ul>
 710      * <li>The first argument is {@code null} or is a string of
 711      * length zero.


 719      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 720      * string is longer than length 1.
 721      *
 722      * <li>The value represented by the string is larger than the
 723      * largest unsigned {@code long}, 2<sup>64</sup>-1.
 724      *
 725      * </ul>
 726      *
 727      *
 728      * @param      s   the {@code String} containing the unsigned integer
 729      *                  representation to be parsed
 730      * @param      radix   the radix to be used while parsing {@code s}.
 731      * @return     the unsigned {@code long} represented by the string
 732      *             argument in the specified radix.
 733      * @throws     NumberFormatException if the {@code String}
 734      *             does not contain a parsable {@code long}.
 735      * @since 1.8
 736      */
 737     public static long parseUnsignedLong(String s, int radix)
 738                 throws NumberFormatException {
 739         requireNonEmpty(s);
 740         return parseUnsignedLong(s, radix, 0);
 741     }
 742 
 743     /**
 744      * Parses the {@link CharSequence} argument as an unsigned {@code long} in
 745      * the specified {@code radix}, beginning at the specified
 746      * {@code beginIndex} and extending to the end of the sequence.
 747      *
 748      * <p>The method does not take steps to guard against the
 749      * {@code CharSequence} being mutated while parsing.
 750      *
 751      * @param      s   the {@code CharSequence} containing the unsigned
 752      *                 {@code long} representation to be parsed
 753      * @param      radix   the radix to be used while parsing {@code s}.
 754      * @param      beginIndex   the beginning index, inclusive.
 755      * @return     the unsigned {@code long} represented by the subsequence in
 756      *             the specified radix.
 757      * @throws     NullPointerException  if {@code s} is null.
 758      * @throws     IllegalArgumentException  if {@code beginIndex} is greater
 759      *             than or equal to {@code s.length()}.
 760      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is negative.
 761      * @throws     NumberFormatException  if the {@code CharSequence} does not
 762      *             contain a parsable unsigned {@code long} in the specified
 763      *             {@code radix}, or if {@code radix} is either smaller than
 764      *             {@link java.lang.Character#MIN_RADIX} or larger than
 765      *             {@link java.lang.Character#MAX_RADIX}.
 766      * @since  1.9
 767      */
 768     public static long parseUnsignedLong(CharSequence s, int radix, int beginIndex)
 769                 throws NumberFormatException {
 770         // forces a null check of s
 771         return parseUnsignedLong(s, radix, beginIndex, s.length());
 772     }
 773 
 774     /**
 775      * Parses the {@link CharSequence} argument as an unsigned {@code long} in
 776      * the specified {@code radix}, beginning at the specified
 777      * {@code beginIndex} and extending to {@code endIndex - 1}.
 778      *
 779      * <p>The method does not take steps to guard against the
 780      * {@code CharSequence} being mutated while parsing.
 781      *
 782      * @param      s   the {@code CharSequence} containing the unsigned
 783      *                 {@code long} representation to be parsed
 784      * @param      radix   the radix to be used while parsing {@code s}.
 785      * @param      beginIndex   the beginning index, inclusive.
 786      * @param      endIndex     the ending index, exclusive.
 787      * @return     the unsigned {@code long} represented by the subsequence in
 788      *             the specified radix.
 789      * @throws     NullPointerException  if {@code s} is null.
 790      * @throws     IllegalArgumentException  if {@code beginIndex} is greater
 791      *             than or equal to {@code endIndex}.
 792      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is
 793      *             negative, {@code endIndex} is negative or {@code endIndex}
 794      *             is greater than {@code s.length()}
 795      * @throws     NumberFormatException  if the {@code CharSequence} does not
 796      *             contain a parsable unsigned {@code long} in the specified
 797      *             {@code radix}, or if {@code radix} is either smaller than
 798      *             {@link java.lang.Character#MIN_RADIX} or larger than
 799      *             {@link java.lang.Character#MAX_RADIX}.
 800      * @since  1.9
 801      */
 802     public static long parseUnsignedLong(CharSequence s, int radix, int beginIndex, int endIndex)
 803                 throws NumberFormatException {
 804         s.getClass(); // null check
 805         if (beginIndex >= endIndex) {
 806             throw new IllegalArgumentException("beginIndex must be less than endIndex");
 807         }
 808         int start = beginIndex, len = endIndex - beginIndex;
 809         if (len > 0) {
 810             char firstChar = s.charAt(start);
 811             if (firstChar == '-') {
 812                 throw new NumberFormatException(String.format("Illegal leading minus sign " +
 813                         "on unsigned string %s.", s.subSequence(start, start + len)));

 814             } else {
 815                 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits
 816                         (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits
 817                     return parseLong(s, radix, start, start + len);
 818                 }
 819 
 820                 // No need for range checks on end due to testing above.
 821                 long first = parseLong(s, radix, start, start + len - 1);
 822                 int second = Character.digit(s.charAt(start + len - 1), radix);
 823                 if (second < 0) {
 824                     throw new NumberFormatException("Bad digit at end of " +
 825                             s.subSequence(start, start + len));
 826                 }
 827                 long result = first * radix + second;
 828 
 829                 /*
 830                  * Test leftmost bits of multiprecision extension of first*radix
 831                  * for overflow. The number of bits needed is defined by
 832                  * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then
 833                  * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and
 834                  * overflow is tested by splitting guard in the ranges
 835                  * guard < 92, 92 <= guard < 128, and 128 <= guard, where
 836                  * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take
 837                  * on a value which does not include a prime factor in the legal
 838                  * radix range.
 839                  */
 840                 int guard = radix * (int) (first >>> 57);
 841                 if (guard >= 128 ||
 842                         (result >= 0 && guard >= 128 - Character.MAX_RADIX)) {
 843                     /*
 844                      * For purposes of exposition, the programmatic statements
 845                      * below should be taken to be multi-precision, i.e., not


 862                      * so that first*radix + second >= 92*2^57 + 0 > 2^63
 863                      *
 864                      * D) Condition guard < 128:
 865                      * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1)
 866                      * so
 867                      * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36
 868                      * thus
 869                      * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36
 870                      * whence
 871                      * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63
 872                      *
 873                      * E) Conditions C, D, and result >= 0:
 874                      * C and D combined imply the mathematical result
 875                      * 2^63 < first*radix + second < 2^64 + 2^63. The lower
 876                      * bound is therefore negative as a signed long, but the
 877                      * upper bound is too small to overflow again after the
 878                      * signed long overflows to positive above 2^64 - 1. Hence
 879                      * result >= 0 implies overflow given C and D.
 880                      */
 881                     throw new NumberFormatException(String.format("String value %s exceeds " +
 882                             "range of unsigned long.", s.subSequence(start, start + len)));
 883                 }
 884                 return result;
 885             }
 886         } else {
 887             throw NumberFormatException.forInputString("");
 888         }
 889     }
 890 
 891     /**
 892      * Parses the string argument as an unsigned decimal {@code long}. The
 893      * characters in the string must all be decimal digits, except
 894      * that the first character may be an an ASCII plus sign {@code
 895      * '+'} ({@code '\u005Cu002B'}). The resulting integer value
 896      * is returned, exactly as if the argument and the radix 10 were
 897      * given as arguments to the {@link
 898      * #parseUnsignedLong(java.lang.String, int)} method.
 899      *
 900      * @param s   a {@code String} containing the unsigned {@code long}
 901      *            representation to be parsed
 902      * @return    the unsigned {@code long} value represented by the decimal string argument
 903      * @throws    NumberFormatException  if the string does not contain a
 904      *            parsable unsigned integer.
 905      * @since 1.8
 906      */
 907     public static long parseUnsignedLong(String s) throws NumberFormatException {
 908         requireNonEmpty(s);
 909         return parseUnsignedLong(s, 10, 0, s.length());
 910     }
 911 
 912     /**
 913      * Returns a {@code Long} object holding the value
 914      * extracted from the specified {@code String} when parsed
 915      * with the radix given by the second argument.  The first
 916      * argument is interpreted as representing a signed
 917      * {@code long} in the radix specified by the second
 918      * argument, exactly as if the arguments were given to the {@link
 919      * #parseLong(java.lang.String, int)} method. The result is a
 920      * {@code Long} object that represents the {@code long}
 921      * value specified by the string.
 922      *
 923      * <p>In other words, this method returns a {@code Long} object equal
 924      * to the value of:
 925      *
 926      * <blockquote>
 927      *  {@code new Long(Long.parseLong(s, radix))}
 928      * </blockquote>
 929      *
 930      * @param      s       the string to be parsed
 931      * @param      radix   the radix to be used in interpreting {@code s}
 932      * @return     a {@code Long} object holding the value
 933      *             represented by the string argument in the specified
 934      *             radix.
 935      * @throws     NumberFormatException  If the {@code String} does not
 936      *             contain a parsable {@code long}.
 937      */
 938     public static Long valueOf(String s, int radix) throws NumberFormatException {
 939         requireNonEmpty(s);
 940         return Long.valueOf(parseLong(s, radix, 0, s.length()));
 941     }
 942 
 943     /**
 944      * Returns a {@code Long} object holding the value
 945      * of the specified {@code String}. The argument is
 946      * interpreted as representing a signed decimal {@code long},
 947      * exactly as if the argument were given to the {@link
 948      * #parseLong(java.lang.String)} method. The result is a
 949      * {@code Long} object that represents the integer value
 950      * specified by the string.
 951      *
 952      * <p>In other words, this method returns a {@code Long} object
 953      * equal to the value of:
 954      *
 955      * <blockquote>
 956      *  {@code new Long(Long.parseLong(s))}
 957      * </blockquote>
 958      *
 959      * @param      s   the string to be parsed.
 960      * @return     a {@code Long} object holding the value
 961      *             represented by the string argument.
 962      * @throws     NumberFormatException  If the string cannot be parsed
 963      *             as a {@code long}.
 964      */
 965     public static Long valueOf(String s) throws NumberFormatException {
 966         requireNonEmpty(s);
 967         return Long.valueOf(parseLong(s, 10, 0, s.length()));
 968     }
 969 
 970     private static class LongCache {
 971         private LongCache(){}
 972 
 973         static final Long cache[] = new Long[-(-128) + 127 + 1];
 974 
 975         static {
 976             for(int i = 0; i < cache.length; i++)
 977                 cache[i] = new Long(i - 128);
 978         }
 979     }
 980 
 981     /**
 982      * Returns a {@code Long} instance representing the specified
 983      * {@code long} value.
 984      * If a new {@code Long} instance is not required, this method
 985      * should generally be used in preference to the constructor
 986      * {@link #Long(long)}, as this method is likely to yield
 987      * significantly better space and time performance by caching


1109      *          {@code Long} object.
1110      */
1111     public Long(long value) {
1112         this.value = value;
1113     }
1114 
1115     /**
1116      * Constructs a newly allocated {@code Long} object that
1117      * represents the {@code long} value indicated by the
1118      * {@code String} parameter. The string is converted to a
1119      * {@code long} value in exactly the manner used by the
1120      * {@code parseLong} method for radix 10.
1121      *
1122      * @param      s   the {@code String} to be converted to a
1123      *             {@code Long}.
1124      * @throws     NumberFormatException  if the {@code String} does not
1125      *             contain a parsable {@code long}.
1126      * @see        java.lang.Long#parseLong(java.lang.String, int)
1127      */
1128     public Long(String s) throws NumberFormatException {
1129         requireNonEmpty(s);
1130         this.value = parseLong(s, 10, 0, s.length());
1131     }
1132 
1133     /**
1134      * Returns the value of this {@code Long} as a {@code byte} after
1135      * a narrowing primitive conversion.
1136      * @jls 5.1.3 Narrowing Primitive Conversions
1137      */
1138     public byte byteValue() {
1139         return (byte)value;
1140     }
1141 
1142     /**
1143      * Returns the value of this {@code Long} as a {@code short} after
1144      * a narrowing primitive conversion.
1145      * @jls 5.1.3 Narrowing Primitive Conversions
1146      */
1147     public short shortValue() {
1148         return (short)value;
1149     }
1150