1 /* 2 * Copyright (c) 1994, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 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.lang.invoke.MethodHandles; 30 import java.lang.constant.Constable; 31 import java.lang.constant.ConstantDesc; 32 import java.math.*; 33 import java.util.Objects; 34 import java.util.Optional; 35 36 import jdk.internal.HotSpotIntrinsicCandidate; 37 import jdk.internal.misc.VM; 38 39 import static java.lang.String.COMPACT_STRINGS; 40 import static java.lang.String.LATIN1; 41 import static java.lang.String.UTF16; 42 43 /** 44 * The {@code Long} class wraps a value of the primitive type {@code 45 * long} in an object. An object of type {@code Long} contains a 46 * single field whose type is {@code long}. 47 * 48 * <p> In addition, this class provides several methods for converting 49 * a {@code long} to a {@code String} and a {@code String} to a {@code 50 * long}, as well as other constants and methods useful when dealing 51 * with a {@code long}. 52 * 53 * <p>Implementation note: The implementations of the "bit twiddling" 54 * methods (such as {@link #highestOneBit(long) highestOneBit} and 55 * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are 56 * based on material from Henry S. Warren, Jr.'s <i>Hacker's 57 * Delight</i>, (Addison Wesley, 2002). 58 * 59 * @author Lee Boynton 60 * @author Arthur van Hoff 61 * @author Josh Bloch 62 * @author Joseph D. Darcy 63 * @since 1.0 64 */ 65 public final class Long extends Number 66 implements Comparable<Long>, Constable, ConstantDesc { 67 /** 68 * A constant holding the minimum value a {@code long} can 69 * have, -2<sup>63</sup>. 70 */ 71 @Native public static final long MIN_VALUE = 0x8000000000000000L; 72 73 /** 74 * A constant holding the maximum value a {@code long} can 75 * have, 2<sup>63</sup>-1. 76 */ 77 @Native public static final long MAX_VALUE = 0x7fffffffffffffffL; 78 79 /** 80 * The {@code Class} instance representing the primitive type 81 * {@code long}. 82 * 83 * @since 1.1 84 */ 85 @SuppressWarnings("unchecked") 86 public static final Class<Long> TYPE = (Class<Long>) Class.getPrimitiveClass("long"); 87 88 /** 89 * Returns a string representation of the first argument in the 90 * radix specified by the second argument. 91 * 92 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 93 * or larger than {@code Character.MAX_RADIX}, then the radix 94 * {@code 10} is used instead. 95 * 96 * <p>If the first argument is negative, the first element of the 97 * result is the ASCII minus sign {@code '-'} 98 * ({@code '\u005Cu002d'}). If the first argument is not 99 * negative, no sign character appears in the result. 100 * 101 * <p>The remaining characters of the result represent the magnitude 102 * of the first argument. If the magnitude is zero, it is 103 * represented by a single zero character {@code '0'} 104 * ({@code '\u005Cu0030'}); otherwise, the first character of 105 * the representation of the magnitude will not be the zero 106 * character. The following ASCII characters are used as digits: 107 * 108 * <blockquote> 109 * {@code 0123456789abcdefghijklmnopqrstuvwxyz} 110 * </blockquote> 111 * 112 * These are {@code '\u005Cu0030'} through 113 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 114 * {@code '\u005Cu007a'}. If {@code radix} is 115 * <var>N</var>, then the first <var>N</var> of these characters 116 * are used as radix-<var>N</var> digits in the order shown. Thus, 117 * the digits for hexadecimal (radix 16) are 118 * {@code 0123456789abcdef}. If uppercase letters are 119 * desired, the {@link java.lang.String#toUpperCase()} method may 120 * be called on the result: 121 * 122 * <blockquote> 123 * {@code Long.toString(n, 16).toUpperCase()} 124 * </blockquote> 125 * 126 * @param i a {@code long} to be converted to a string. 127 * @param radix the radix to use in the string representation. 128 * @return a string representation of the argument in the specified radix. 129 * @see java.lang.Character#MAX_RADIX 130 * @see java.lang.Character#MIN_RADIX 131 */ 132 public static String toString(long i, int radix) { 133 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 134 radix = 10; 135 if (radix == 10) 136 return toString(i); 137 138 if (COMPACT_STRINGS) { 139 byte[] buf = new byte[65]; 140 int charPos = 64; 141 boolean negative = (i < 0); 142 143 if (!negative) { 144 i = -i; 145 } 146 147 while (i <= -radix) { 148 buf[charPos--] = (byte)Integer.digits[(int)(-(i % radix))]; 149 i = i / radix; 150 } 151 buf[charPos] = (byte)Integer.digits[(int)(-i)]; 152 153 if (negative) { 154 buf[--charPos] = '-'; 155 } 156 return StringLatin1.newString(buf, charPos, (65 - charPos)); 157 } 158 return toStringUTF16(i, radix); 159 } 160 161 private static String toStringUTF16(long i, int radix) { 162 byte[] buf = new byte[65 * 2]; 163 int charPos = 64; 164 boolean negative = (i < 0); 165 if (!negative) { 166 i = -i; 167 } 168 while (i <= -radix) { 169 StringUTF16.putChar(buf, charPos--, Integer.digits[(int)(-(i % radix))]); 170 i = i / radix; 171 } 172 StringUTF16.putChar(buf, charPos, Integer.digits[(int)(-i)]); 173 if (negative) { 174 StringUTF16.putChar(buf, --charPos, '-'); 175 } 176 return StringUTF16.newString(buf, charPos, (65 - charPos)); 177 } 178 179 /** 180 * Returns a string representation of the first argument as an 181 * unsigned integer value in the radix specified by the second 182 * argument. 183 * 184 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 185 * or larger than {@code Character.MAX_RADIX}, then the radix 186 * {@code 10} is used instead. 187 * 188 * <p>Note that since the first argument is treated as an unsigned 189 * value, no leading sign character is printed. 190 * 191 * <p>If the magnitude is zero, it is represented by a single zero 192 * character {@code '0'} ({@code '\u005Cu0030'}); otherwise, 193 * the first character of the representation of the magnitude will 194 * not be the zero character. 195 * 196 * <p>The behavior of radixes and the characters used as digits 197 * are the same as {@link #toString(long, int) toString}. 198 * 199 * @param i an integer to be converted to an unsigned string. 200 * @param radix the radix to use in the string representation. 201 * @return an unsigned string representation of the argument in the specified radix. 202 * @see #toString(long, int) 203 * @since 1.8 204 */ 205 public static String toUnsignedString(long i, int radix) { 206 if (i >= 0) 207 return toString(i, radix); 208 else { 209 switch (radix) { 210 case 2: 211 return toBinaryString(i); 212 213 case 4: 214 return toUnsignedString0(i, 2); 215 216 case 8: 217 return toOctalString(i); 218 219 case 10: 220 /* 221 * We can get the effect of an unsigned division by 10 222 * on a long value by first shifting right, yielding a 223 * positive value, and then dividing by 5. This 224 * allows the last digit and preceding digits to be 225 * isolated more quickly than by an initial conversion 226 * to BigInteger. 227 */ 228 long quot = (i >>> 1) / 5; 229 long rem = i - quot * 10; 230 return toString(quot) + rem; 231 232 case 16: 233 return toHexString(i); 234 235 case 32: 236 return toUnsignedString0(i, 5); 237 238 default: 239 return toUnsignedBigInteger(i).toString(radix); 240 } 241 } 242 } 243 244 /** 245 * Return a BigInteger equal to the unsigned value of the 246 * argument. 247 */ 248 private static BigInteger toUnsignedBigInteger(long i) { 249 if (i >= 0L) 250 return BigInteger.valueOf(i); 251 else { 252 int upper = (int) (i >>> 32); 253 int lower = (int) i; 254 255 // return (upper << 32) + lower 256 return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32). 257 add(BigInteger.valueOf(Integer.toUnsignedLong(lower))); 258 } 259 } 260 261 /** 262 * Returns a string representation of the {@code long} 263 * argument as an unsigned integer in base 16. 264 * 265 * <p>The unsigned {@code long} value is the argument plus 266 * 2<sup>64</sup> if the argument is negative; otherwise, it is 267 * equal to the argument. This value is converted to a string of 268 * ASCII digits in hexadecimal (base 16) with no extra 269 * leading {@code 0}s. 270 * 271 * <p>The value of the argument can be recovered from the returned 272 * string {@code s} by calling {@link 273 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s, 274 * 16)}. 275 * 276 * <p>If the unsigned magnitude is zero, it is represented by a 277 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 278 * otherwise, the first character of the representation of the 279 * unsigned magnitude will not be the zero character. The 280 * following characters are used as hexadecimal digits: 281 * 282 * <blockquote> 283 * {@code 0123456789abcdef} 284 * </blockquote> 285 * 286 * These are the characters {@code '\u005Cu0030'} through 287 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 288 * {@code '\u005Cu0066'}. If uppercase letters are desired, 289 * the {@link java.lang.String#toUpperCase()} method may be called 290 * on the result: 291 * 292 * <blockquote> 293 * {@code Long.toHexString(n).toUpperCase()} 294 * </blockquote> 295 * 296 * @param i a {@code long} to be converted to a string. 297 * @return the string representation of the unsigned {@code long} 298 * value represented by the argument in hexadecimal 299 * (base 16). 300 * @see #parseUnsignedLong(String, int) 301 * @see #toUnsignedString(long, int) 302 * @since 1.0.2 303 */ 304 public static String toHexString(long i) { 305 return toUnsignedString0(i, 4); 306 } 307 308 /** 309 * Returns a string representation of the {@code long} 310 * argument as an unsigned integer in base 8. 311 * 312 * <p>The unsigned {@code long} value is the argument plus 313 * 2<sup>64</sup> if the argument is negative; otherwise, it is 314 * equal to the argument. This value is converted to a string of 315 * ASCII digits in octal (base 8) with no extra leading 316 * {@code 0}s. 317 * 318 * <p>The value of the argument can be recovered from the returned 319 * string {@code s} by calling {@link 320 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s, 321 * 8)}. 322 * 323 * <p>If the unsigned magnitude is zero, it is represented by a 324 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 325 * otherwise, the first character of the representation of the 326 * unsigned magnitude will not be the zero character. The 327 * following characters are used as octal digits: 328 * 329 * <blockquote> 330 * {@code 01234567} 331 * </blockquote> 332 * 333 * These are the characters {@code '\u005Cu0030'} through 334 * {@code '\u005Cu0037'}. 335 * 336 * @param i a {@code long} to be converted to a string. 337 * @return the string representation of the unsigned {@code long} 338 * value represented by the argument in octal (base 8). 339 * @see #parseUnsignedLong(String, int) 340 * @see #toUnsignedString(long, int) 341 * @since 1.0.2 342 */ 343 public static String toOctalString(long i) { 344 return toUnsignedString0(i, 3); 345 } 346 347 /** 348 * Returns a string representation of the {@code long} 349 * argument as an unsigned integer in base 2. 350 * 351 * <p>The unsigned {@code long} value is the argument plus 352 * 2<sup>64</sup> if the argument is negative; otherwise, it is 353 * equal to the argument. This value is converted to a string of 354 * ASCII digits in binary (base 2) with no extra leading 355 * {@code 0}s. 356 * 357 * <p>The value of the argument can be recovered from the returned 358 * string {@code s} by calling {@link 359 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s, 360 * 2)}. 361 * 362 * <p>If the unsigned magnitude is zero, it is represented by a 363 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 364 * otherwise, the first character of the representation of the 365 * unsigned magnitude will not be the zero character. The 366 * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code 367 * '1'} ({@code '\u005Cu0031'}) are used as binary digits. 368 * 369 * @param i a {@code long} to be converted to a string. 370 * @return the string representation of the unsigned {@code long} 371 * value represented by the argument in binary (base 2). 372 * @see #parseUnsignedLong(String, int) 373 * @see #toUnsignedString(long, int) 374 * @since 1.0.2 375 */ 376 public static String toBinaryString(long i) { 377 return toUnsignedString0(i, 1); 378 } 379 380 /** 381 * Format a long (treated as unsigned) into a String. 382 * @param val the value to format 383 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 384 */ 385 static String toUnsignedString0(long val, int shift) { 386 // assert shift > 0 && shift <=5 : "Illegal shift value"; 387 int mag = Long.SIZE - Long.numberOfLeadingZeros(val); 388 int chars = Math.max(((mag + (shift - 1)) / shift), 1); 389 if (COMPACT_STRINGS) { 390 byte[] buf = new byte[chars]; 391 formatUnsignedLong0(val, shift, buf, 0, chars); 392 return new String(buf, LATIN1); 393 } else { 394 byte[] buf = new byte[chars * 2]; 395 formatUnsignedLong0UTF16(val, shift, buf, 0, chars); 396 return new String(buf, UTF16); 397 } 398 } 399 400 /** 401 * Format a long (treated as unsigned) into a character buffer. If 402 * {@code len} exceeds the formatted ASCII representation of {@code val}, 403 * {@code buf} will be padded with leading zeroes. 404 * 405 * @param val the unsigned long to format 406 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 407 * @param buf the character buffer to write to 408 * @param offset the offset in the destination buffer to start at 409 * @param len the number of characters to write 410 */ 411 412 /** byte[]/LATIN1 version */ 413 static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) { 414 int charPos = offset + len; 415 int radix = 1 << shift; 416 int mask = radix - 1; 417 do { 418 buf[--charPos] = (byte)Integer.digits[((int) val) & mask]; 419 val >>>= shift; 420 } while (charPos > offset); 421 } 422 423 /** byte[]/UTF16 version */ 424 private static void formatUnsignedLong0UTF16(long val, int shift, byte[] buf, int offset, int len) { 425 int charPos = offset + len; 426 int radix = 1 << shift; 427 int mask = radix - 1; 428 do { 429 StringUTF16.putChar(buf, --charPos, Integer.digits[((int) val) & mask]); 430 val >>>= shift; 431 } while (charPos > offset); 432 } 433 434 static String fastUUID(long lsb, long msb) { 435 if (COMPACT_STRINGS) { 436 byte[] buf = new byte[36]; 437 formatUnsignedLong0(lsb, 4, buf, 24, 12); 438 formatUnsignedLong0(lsb >>> 48, 4, buf, 19, 4); 439 formatUnsignedLong0(msb, 4, buf, 14, 4); 440 formatUnsignedLong0(msb >>> 16, 4, buf, 9, 4); 441 formatUnsignedLong0(msb >>> 32, 4, buf, 0, 8); 442 443 buf[23] = '-'; 444 buf[18] = '-'; 445 buf[13] = '-'; 446 buf[8] = '-'; 447 448 return new String(buf, LATIN1); 449 } else { 450 byte[] buf = new byte[72]; 451 452 formatUnsignedLong0UTF16(lsb, 4, buf, 24, 12); 453 formatUnsignedLong0UTF16(lsb >>> 48, 4, buf, 19, 4); 454 formatUnsignedLong0UTF16(msb, 4, buf, 14, 4); 455 formatUnsignedLong0UTF16(msb >>> 16, 4, buf, 9, 4); 456 formatUnsignedLong0UTF16(msb >>> 32, 4, buf, 0, 8); 457 458 StringUTF16.putChar(buf, 23, '-'); 459 StringUTF16.putChar(buf, 18, '-'); 460 StringUTF16.putChar(buf, 13, '-'); 461 StringUTF16.putChar(buf, 8, '-'); 462 463 return new String(buf, UTF16); 464 } 465 } 466 467 /** 468 * Returns a {@code String} object representing the specified 469 * {@code long}. The argument is converted to signed decimal 470 * representation and returned as a string, exactly as if the 471 * argument and the radix 10 were given as arguments to the {@link 472 * #toString(long, int)} method. 473 * 474 * @param i a {@code long} to be converted. 475 * @return a string representation of the argument in base 10. 476 */ 477 public static String toString(long i) { 478 int size = stringSize(i); 479 if (COMPACT_STRINGS) { 480 byte[] buf = new byte[size]; 481 getChars(i, size, buf); 482 return new String(buf, LATIN1); 483 } else { 484 byte[] buf = new byte[size * 2]; 485 StringUTF16.getChars(i, size, buf); 486 return new String(buf, UTF16); 487 } 488 } 489 490 /** 491 * Returns a string representation of the argument as an unsigned 492 * decimal value. 493 * 494 * The argument is converted to unsigned decimal representation 495 * and returned as a string exactly as if the argument and radix 496 * 10 were given as arguments to the {@link #toUnsignedString(long, 497 * int)} method. 498 * 499 * @param i an integer to be converted to an unsigned string. 500 * @return an unsigned string representation of the argument. 501 * @see #toUnsignedString(long, int) 502 * @since 1.8 503 */ 504 public static String toUnsignedString(long i) { 505 return toUnsignedString(i, 10); 506 } 507 508 /** 509 * Places characters representing the long i into the 510 * character array buf. The characters are placed into 511 * the buffer backwards starting with the least significant 512 * digit at the specified index (exclusive), and working 513 * backwards from there. 514 * 515 * @implNote This method converts positive inputs into negative 516 * values, to cover the Long.MIN_VALUE case. Converting otherwise 517 * (negative to positive) will expose -Long.MIN_VALUE that overflows 518 * long. 519 * 520 * @param i value to convert 521 * @param index next index, after the least significant digit 522 * @param buf target buffer, Latin1-encoded 523 * @return index of the most significant digit or minus sign, if present 524 */ 525 static int getChars(long i, int index, byte[] buf) { 526 long q; 527 int r; 528 int charPos = index; 529 530 boolean negative = (i < 0); 531 if (!negative) { 532 i = -i; 533 } 534 535 // Get 2 digits/iteration using longs until quotient fits into an int 536 while (i <= Integer.MIN_VALUE) { 537 q = i / 100; 538 r = (int)((q * 100) - i); 539 i = q; 540 buf[--charPos] = Integer.DigitOnes[r]; 541 buf[--charPos] = Integer.DigitTens[r]; 542 } 543 544 // Get 2 digits/iteration using ints 545 int q2; 546 int i2 = (int)i; 547 while (i2 <= -100) { 548 q2 = i2 / 100; 549 r = (q2 * 100) - i2; 550 i2 = q2; 551 buf[--charPos] = Integer.DigitOnes[r]; 552 buf[--charPos] = Integer.DigitTens[r]; 553 } 554 555 // We know there are at most two digits left at this point. 556 q2 = i2 / 10; 557 r = (q2 * 10) - i2; 558 buf[--charPos] = (byte)('0' + r); 559 560 // Whatever left is the remaining digit. 561 if (q2 < 0) { 562 buf[--charPos] = (byte)('0' - q2); 563 } 564 565 if (negative) { 566 buf[--charPos] = (byte)'-'; 567 } 568 return charPos; 569 } 570 571 /** 572 * Returns the string representation size for a given long value. 573 * 574 * @param x long value 575 * @return string size 576 * 577 * @implNote There are other ways to compute this: e.g. binary search, 578 * but values are biased heavily towards zero, and therefore linear search 579 * wins. The iteration results are also routinely inlined in the generated 580 * code after loop unrolling. 581 */ 582 static int stringSize(long x) { 583 int d = 1; 584 if (x >= 0) { 585 d = 0; 586 x = -x; 587 } 588 long p = -10; 589 for (int i = 1; i < 19; i++) { 590 if (x > p) 591 return i + d; 592 p = 10 * p; 593 } 594 return 19 + d; 595 } 596 597 /** 598 * Parses the string argument as a signed {@code long} in the 599 * radix specified by the second argument. The characters in the 600 * string must all be digits of the specified radix (as determined 601 * by whether {@link java.lang.Character#digit(char, int)} returns 602 * a nonnegative value), except that the first character may be an 603 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to 604 * indicate a negative value or an ASCII plus sign {@code '+'} 605 * ({@code '\u005Cu002B'}) to indicate a positive value. The 606 * resulting {@code long} value is returned. 607 * 608 * <p>Note that neither the character {@code L} 609 * ({@code '\u005Cu004C'}) nor {@code l} 610 * ({@code '\u005Cu006C'}) is permitted to appear at the end 611 * of the string as a type indicator, as would be permitted in 612 * Java programming language source code - except that either 613 * {@code L} or {@code l} may appear as a digit for a 614 * radix greater than or equal to 22. 615 * 616 * <p>An exception of type {@code NumberFormatException} is 617 * thrown if any of the following situations occurs: 618 * <ul> 619 * 620 * <li>The first argument is {@code null} or is a string of 621 * length zero. 622 * 623 * <li>The {@code radix} is either smaller than {@link 624 * java.lang.Character#MIN_RADIX} or larger than {@link 625 * java.lang.Character#MAX_RADIX}. 626 * 627 * <li>Any character of the string is not a digit of the specified 628 * radix, except that the first character may be a minus sign 629 * {@code '-'} ({@code '\u005Cu002d'}) or plus sign {@code 630 * '+'} ({@code '\u005Cu002B'}) provided that the string is 631 * longer than length 1. 632 * 633 * <li>The value represented by the string is not a value of type 634 * {@code long}. 635 * </ul> 636 * 637 * <p>Examples: 638 * <blockquote><pre> 639 * parseLong("0", 10) returns 0L 640 * parseLong("473", 10) returns 473L 641 * parseLong("+42", 10) returns 42L 642 * parseLong("-0", 10) returns 0L 643 * parseLong("-FF", 16) returns -255L 644 * parseLong("1100110", 2) returns 102L 645 * parseLong("99", 8) throws a NumberFormatException 646 * parseLong("Hazelnut", 10) throws a NumberFormatException 647 * parseLong("Hazelnut", 36) returns 1356099454469L 648 * </pre></blockquote> 649 * 650 * @param s the {@code String} containing the 651 * {@code long} representation to be parsed. 652 * @param radix the radix to be used while parsing {@code s}. 653 * @return the {@code long} represented by the string argument in 654 * the specified radix. 655 * @throws NumberFormatException if the string does not contain a 656 * parsable {@code long}. 657 */ 658 public static long parseLong(String s, int radix) 659 throws NumberFormatException 660 { 661 if (s == null) { 662 throw new NumberFormatException("null"); 663 } 664 665 if (radix < Character.MIN_RADIX) { 666 throw new NumberFormatException("radix " + radix + 667 " less than Character.MIN_RADIX"); 668 } 669 if (radix > Character.MAX_RADIX) { 670 throw new NumberFormatException("radix " + radix + 671 " greater than Character.MAX_RADIX"); 672 } 673 674 boolean negative = false; 675 int i = 0, len = s.length(); 676 long limit = -Long.MAX_VALUE; 677 678 if (len > 0) { 679 char firstChar = s.charAt(0); 680 if (firstChar < '0') { // Possible leading "+" or "-" 681 if (firstChar == '-') { 682 negative = true; 683 limit = Long.MIN_VALUE; 684 } else if (firstChar != '+') { 685 throw NumberFormatException.forInputString(s, radix); 686 } 687 688 if (len == 1) { // Cannot have lone "+" or "-" 689 throw NumberFormatException.forInputString(s, radix); 690 } 691 i++; 692 } 693 long multmin = limit / radix; 694 long result = 0; 695 while (i < len) { 696 // Accumulating negatively avoids surprises near MAX_VALUE 697 int digit = Character.digit(s.charAt(i++),radix); 698 if (digit < 0 || result < multmin) { 699 throw NumberFormatException.forInputString(s, radix); 700 } 701 result *= radix; 702 if (result < limit + digit) { 703 throw NumberFormatException.forInputString(s, radix); 704 } 705 result -= digit; 706 } 707 return negative ? result : -result; 708 } else { 709 throw NumberFormatException.forInputString(s, radix); 710 } 711 } 712 713 /** 714 * Parses the {@link CharSequence} argument as a signed {@code long} in 715 * the specified {@code radix}, beginning at the specified 716 * {@code beginIndex} and extending to {@code endIndex - 1}. 717 * 718 * <p>The method does not take steps to guard against the 719 * {@code CharSequence} being mutated while parsing. 720 * 721 * @param s the {@code CharSequence} containing the {@code long} 722 * representation to be parsed 723 * @param beginIndex the beginning index, inclusive. 724 * @param endIndex the ending index, exclusive. 725 * @param radix the radix to be used while parsing {@code s}. 726 * @return the signed {@code long} represented by the subsequence in 727 * the specified radix. 728 * @throws NullPointerException if {@code s} is null. 729 * @throws IndexOutOfBoundsException if {@code beginIndex} is 730 * negative, or if {@code beginIndex} is greater than 731 * {@code endIndex} or if {@code endIndex} is greater than 732 * {@code s.length()}. 733 * @throws NumberFormatException if the {@code CharSequence} does not 734 * contain a parsable {@code int} in the specified 735 * {@code radix}, or if {@code radix} is either smaller than 736 * {@link java.lang.Character#MIN_RADIX} or larger than 737 * {@link java.lang.Character#MAX_RADIX}. 738 * @since 9 739 */ 740 public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix) 741 throws NumberFormatException { 742 s = Objects.requireNonNull(s); 743 744 if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) { 745 throw new IndexOutOfBoundsException(); 746 } 747 if (radix < Character.MIN_RADIX) { 748 throw new NumberFormatException("radix " + radix + 749 " less than Character.MIN_RADIX"); 750 } 751 if (radix > Character.MAX_RADIX) { 752 throw new NumberFormatException("radix " + radix + 753 " greater than Character.MAX_RADIX"); 754 } 755 756 boolean negative = false; 757 int i = beginIndex; 758 long limit = -Long.MAX_VALUE; 759 760 if (i < endIndex) { 761 char firstChar = s.charAt(i); 762 if (firstChar < '0') { // Possible leading "+" or "-" 763 if (firstChar == '-') { 764 negative = true; 765 limit = Long.MIN_VALUE; 766 } else if (firstChar != '+') { 767 throw NumberFormatException.forCharSequence(s, beginIndex, 768 endIndex, i); 769 } 770 i++; 771 } 772 if (i >= endIndex) { // Cannot have lone "+", "-" or "" 773 throw NumberFormatException.forCharSequence(s, beginIndex, 774 endIndex, i); 775 } 776 long multmin = limit / radix; 777 long result = 0; 778 while (i < endIndex) { 779 // Accumulating negatively avoids surprises near MAX_VALUE 780 int digit = Character.digit(s.charAt(i), radix); 781 if (digit < 0 || result < multmin) { 782 throw NumberFormatException.forCharSequence(s, beginIndex, 783 endIndex, i); 784 } 785 result *= radix; 786 if (result < limit + digit) { 787 throw NumberFormatException.forCharSequence(s, beginIndex, 788 endIndex, i); 789 } 790 i++; 791 result -= digit; 792 } 793 return negative ? result : -result; 794 } else { 795 throw new NumberFormatException(""); 796 } 797 } 798 799 /** 800 * Parses the string argument as a signed decimal {@code long}. 801 * The characters in the string must all be decimal digits, except 802 * that the first character may be an ASCII minus sign {@code '-'} 803 * ({@code \u005Cu002D'}) to indicate a negative value or an 804 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 805 * indicate a positive value. The resulting {@code long} value is 806 * returned, exactly as if the argument and the radix {@code 10} 807 * were given as arguments to the {@link 808 * #parseLong(java.lang.String, int)} method. 809 * 810 * <p>Note that neither the character {@code L} 811 * ({@code '\u005Cu004C'}) nor {@code l} 812 * ({@code '\u005Cu006C'}) is permitted to appear at the end 813 * of the string as a type indicator, as would be permitted in 814 * Java programming language source code. 815 * 816 * @param s a {@code String} containing the {@code long} 817 * representation to be parsed 818 * @return the {@code long} represented by the argument in 819 * decimal. 820 * @throws NumberFormatException if the string does not contain a 821 * parsable {@code long}. 822 */ 823 public static long parseLong(String s) throws NumberFormatException { 824 return parseLong(s, 10); 825 } 826 827 /** 828 * Parses the string argument as an unsigned {@code long} in the 829 * radix specified by the second argument. An unsigned integer 830 * maps the values usually associated with negative numbers to 831 * positive numbers larger than {@code MAX_VALUE}. 832 * 833 * The characters in the string must all be digits of the 834 * specified radix (as determined by whether {@link 835 * java.lang.Character#digit(char, int)} returns a nonnegative 836 * value), except that the first character may be an ASCII plus 837 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 838 * integer value is returned. 839 * 840 * <p>An exception of type {@code NumberFormatException} is 841 * thrown if any of the following situations occurs: 842 * <ul> 843 * <li>The first argument is {@code null} or is a string of 844 * length zero. 845 * 846 * <li>The radix is either smaller than 847 * {@link java.lang.Character#MIN_RADIX} or 848 * larger than {@link java.lang.Character#MAX_RADIX}. 849 * 850 * <li>Any character of the string is not a digit of the specified 851 * radix, except that the first character may be a plus sign 852 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 853 * string is longer than length 1. 854 * 855 * <li>The value represented by the string is larger than the 856 * largest unsigned {@code long}, 2<sup>64</sup>-1. 857 * 858 * </ul> 859 * 860 * 861 * @param s the {@code String} containing the unsigned integer 862 * representation to be parsed 863 * @param radix the radix to be used while parsing {@code s}. 864 * @return the unsigned {@code long} represented by the string 865 * argument in the specified radix. 866 * @throws NumberFormatException if the {@code String} 867 * does not contain a parsable {@code long}. 868 * @since 1.8 869 */ 870 public static long parseUnsignedLong(String s, int radix) 871 throws NumberFormatException { 872 if (s == null) { 873 throw new NumberFormatException("null"); 874 } 875 876 int len = s.length(); 877 if (len > 0) { 878 char firstChar = s.charAt(0); 879 if (firstChar == '-') { 880 throw new 881 NumberFormatException(String.format("Illegal leading minus sign " + 882 "on unsigned string %s.", s)); 883 } else { 884 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits 885 (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits 886 return parseLong(s, radix); 887 } 888 889 // No need for range checks on len due to testing above. 890 long first = parseLong(s, 0, len - 1, radix); 891 int second = Character.digit(s.charAt(len - 1), radix); 892 if (second < 0) { 893 throw new NumberFormatException("Bad digit at end of " + s); 894 } 895 long result = first * radix + second; 896 897 /* 898 * Test leftmost bits of multiprecision extension of first*radix 899 * for overflow. The number of bits needed is defined by 900 * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then 901 * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and 902 * overflow is tested by splitting guard in the ranges 903 * guard < 92, 92 <= guard < 128, and 128 <= guard, where 904 * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take 905 * on a value which does not include a prime factor in the legal 906 * radix range. 907 */ 908 int guard = radix * (int) (first >>> 57); 909 if (guard >= 128 || 910 (result >= 0 && guard >= 128 - Character.MAX_RADIX)) { 911 /* 912 * For purposes of exposition, the programmatic statements 913 * below should be taken to be multi-precision, i.e., not 914 * subject to overflow. 915 * 916 * A) Condition guard >= 128: 917 * If guard >= 128 then first*radix >= 2^7 * 2^57 = 2^64 918 * hence always overflow. 919 * 920 * B) Condition guard < 92: 921 * Define left7 = first >>> 57. 922 * Given first = (left7 * 2^57) + (first & (2^57 - 1)) then 923 * result <= (radix*left7)*2^57 + radix*(2^57 - 1) + second. 924 * Thus if radix*left7 < 92, radix <= 36, and second < 36, 925 * then result < 92*2^57 + 36*(2^57 - 1) + 36 = 2^64 hence 926 * never overflow. 927 * 928 * C) Condition 92 <= guard < 128: 929 * first*radix + second >= radix*left7*2^57 + second 930 * so that first*radix + second >= 92*2^57 + 0 > 2^63 931 * 932 * D) Condition guard < 128: 933 * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1) 934 * so 935 * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36 936 * thus 937 * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36 938 * whence 939 * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63 940 * 941 * E) Conditions C, D, and result >= 0: 942 * C and D combined imply the mathematical result 943 * 2^63 < first*radix + second < 2^64 + 2^63. The lower 944 * bound is therefore negative as a signed long, but the 945 * upper bound is too small to overflow again after the 946 * signed long overflows to positive above 2^64 - 1. Hence 947 * result >= 0 implies overflow given C and D. 948 */ 949 throw new NumberFormatException(String.format("String value %s exceeds " + 950 "range of unsigned long.", s)); 951 } 952 return result; 953 } 954 } else { 955 throw NumberFormatException.forInputString(s, radix); 956 } 957 } 958 959 /** 960 * Parses the {@link CharSequence} argument as an unsigned {@code long} in 961 * the specified {@code radix}, beginning at the specified 962 * {@code beginIndex} and extending to {@code endIndex - 1}. 963 * 964 * <p>The method does not take steps to guard against the 965 * {@code CharSequence} being mutated while parsing. 966 * 967 * @param s the {@code CharSequence} containing the unsigned 968 * {@code long} representation to be parsed 969 * @param beginIndex the beginning index, inclusive. 970 * @param endIndex the ending index, exclusive. 971 * @param radix the radix to be used while parsing {@code s}. 972 * @return the unsigned {@code long} represented by the subsequence in 973 * the specified radix. 974 * @throws NullPointerException if {@code s} is null. 975 * @throws IndexOutOfBoundsException if {@code beginIndex} is 976 * negative, or if {@code beginIndex} is greater than 977 * {@code endIndex} or if {@code endIndex} is greater than 978 * {@code s.length()}. 979 * @throws NumberFormatException if the {@code CharSequence} does not 980 * contain a parsable unsigned {@code long} in the specified 981 * {@code radix}, or if {@code radix} is either smaller than 982 * {@link java.lang.Character#MIN_RADIX} or larger than 983 * {@link java.lang.Character#MAX_RADIX}. 984 * @since 9 985 */ 986 public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix) 987 throws NumberFormatException { 988 s = Objects.requireNonNull(s); 989 990 if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) { 991 throw new IndexOutOfBoundsException(); 992 } 993 int start = beginIndex, len = endIndex - beginIndex; 994 995 if (len > 0) { 996 char firstChar = s.charAt(start); 997 if (firstChar == '-') { 998 throw new NumberFormatException(String.format("Illegal leading minus sign " + 999 "on unsigned string %s.", s.subSequence(start, start + len))); 1000 } else { 1001 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits 1002 (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits 1003 return parseLong(s, start, start + len, radix); 1004 } 1005 1006 // No need for range checks on end due to testing above. 1007 long first = parseLong(s, start, start + len - 1, radix); 1008 int second = Character.digit(s.charAt(start + len - 1), radix); 1009 if (second < 0) { 1010 throw new NumberFormatException("Bad digit at end of " + 1011 s.subSequence(start, start + len)); 1012 } 1013 long result = first * radix + second; 1014 1015 /* 1016 * Test leftmost bits of multiprecision extension of first*radix 1017 * for overflow. The number of bits needed is defined by 1018 * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then 1019 * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and 1020 * overflow is tested by splitting guard in the ranges 1021 * guard < 92, 92 <= guard < 128, and 128 <= guard, where 1022 * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take 1023 * on a value which does not include a prime factor in the legal 1024 * radix range. 1025 */ 1026 int guard = radix * (int) (first >>> 57); 1027 if (guard >= 128 || 1028 (result >= 0 && guard >= 128 - Character.MAX_RADIX)) { 1029 /* 1030 * For purposes of exposition, the programmatic statements 1031 * below should be taken to be multi-precision, i.e., not 1032 * subject to overflow. 1033 * 1034 * A) Condition guard >= 128: 1035 * If guard >= 128 then first*radix >= 2^7 * 2^57 = 2^64 1036 * hence always overflow. 1037 * 1038 * B) Condition guard < 92: 1039 * Define left7 = first >>> 57. 1040 * Given first = (left7 * 2^57) + (first & (2^57 - 1)) then 1041 * result <= (radix*left7)*2^57 + radix*(2^57 - 1) + second. 1042 * Thus if radix*left7 < 92, radix <= 36, and second < 36, 1043 * then result < 92*2^57 + 36*(2^57 - 1) + 36 = 2^64 hence 1044 * never overflow. 1045 * 1046 * C) Condition 92 <= guard < 128: 1047 * first*radix + second >= radix*left7*2^57 + second 1048 * so that first*radix + second >= 92*2^57 + 0 > 2^63 1049 * 1050 * D) Condition guard < 128: 1051 * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1) 1052 * so 1053 * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36 1054 * thus 1055 * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36 1056 * whence 1057 * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63 1058 * 1059 * E) Conditions C, D, and result >= 0: 1060 * C and D combined imply the mathematical result 1061 * 2^63 < first*radix + second < 2^64 + 2^63. The lower 1062 * bound is therefore negative as a signed long, but the 1063 * upper bound is too small to overflow again after the 1064 * signed long overflows to positive above 2^64 - 1. Hence 1065 * result >= 0 implies overflow given C and D. 1066 */ 1067 throw new NumberFormatException(String.format("String value %s exceeds " + 1068 "range of unsigned long.", s.subSequence(start, start + len))); 1069 } 1070 return result; 1071 } 1072 } else { 1073 throw NumberFormatException.forInputString("", radix); 1074 } 1075 } 1076 1077 /** 1078 * Parses the string argument as an unsigned decimal {@code long}. The 1079 * characters in the string must all be decimal digits, except 1080 * that the first character may be an ASCII plus sign {@code 1081 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 1082 * is returned, exactly as if the argument and the radix 10 were 1083 * given as arguments to the {@link 1084 * #parseUnsignedLong(java.lang.String, int)} method. 1085 * 1086 * @param s a {@code String} containing the unsigned {@code long} 1087 * representation to be parsed 1088 * @return the unsigned {@code long} value represented by the decimal string argument 1089 * @throws NumberFormatException if the string does not contain a 1090 * parsable unsigned integer. 1091 * @since 1.8 1092 */ 1093 public static long parseUnsignedLong(String s) throws NumberFormatException { 1094 return parseUnsignedLong(s, 10); 1095 } 1096 1097 /** 1098 * Returns a {@code Long} object holding the value 1099 * extracted from the specified {@code String} when parsed 1100 * with the radix given by the second argument. The first 1101 * argument is interpreted as representing a signed 1102 * {@code long} in the radix specified by the second 1103 * argument, exactly as if the arguments were given to the {@link 1104 * #parseLong(java.lang.String, int)} method. The result is a 1105 * {@code Long} object that represents the {@code long} 1106 * value specified by the string. 1107 * 1108 * <p>In other words, this method returns a {@code Long} object equal 1109 * to the value of: 1110 * 1111 * <blockquote> 1112 * {@code new Long(Long.parseLong(s, radix))} 1113 * </blockquote> 1114 * 1115 * @param s the string to be parsed 1116 * @param radix the radix to be used in interpreting {@code s} 1117 * @return a {@code Long} object holding the value 1118 * represented by the string argument in the specified 1119 * radix. 1120 * @throws NumberFormatException If the {@code String} does not 1121 * contain a parsable {@code long}. 1122 */ 1123 public static Long valueOf(String s, int radix) throws NumberFormatException { 1124 return Long.valueOf(parseLong(s, radix)); 1125 } 1126 1127 /** 1128 * Returns a {@code Long} object holding the value 1129 * of the specified {@code String}. The argument is 1130 * interpreted as representing a signed decimal {@code long}, 1131 * exactly as if the argument were given to the {@link 1132 * #parseLong(java.lang.String)} method. The result is a 1133 * {@code Long} object that represents the integer value 1134 * specified by the string. 1135 * 1136 * <p>In other words, this method returns a {@code Long} object 1137 * equal to the value of: 1138 * 1139 * <blockquote> 1140 * {@code new Long(Long.parseLong(s))} 1141 * </blockquote> 1142 * 1143 * @param s the string to be parsed. 1144 * @return a {@code Long} object holding the value 1145 * represented by the string argument. 1146 * @throws NumberFormatException If the string cannot be parsed 1147 * as a {@code long}. 1148 */ 1149 public static Long valueOf(String s) throws NumberFormatException 1150 { 1151 return Long.valueOf(parseLong(s, 10)); 1152 } 1153 1154 private static class LongCache { 1155 private LongCache() {} 1156 1157 static final Long[] cache; 1158 static Long[] archivedCache; 1159 1160 static { 1161 int size = -(-128) + 127 + 1; 1162 1163 // Load and use the archived cache if it exists 1164 VM.initializeFromArchive(LongCache.class); 1165 if (archivedCache == null || archivedCache.length != size) { 1166 Long[] c = new Long[size]; 1167 long value = -128; 1168 for(int i = 0; i < size; i++) { 1169 c[i] = new Long(value++); 1170 } 1171 archivedCache = c; 1172 } 1173 cache = archivedCache; 1174 } 1175 } 1176 1177 /** 1178 * Returns a {@code Long} instance representing the specified 1179 * {@code long} value. 1180 * If a new {@code Long} instance is not required, this method 1181 * should generally be used in preference to the constructor 1182 * {@link #Long(long)}, as this method is likely to yield 1183 * significantly better space and time performance by caching 1184 * frequently requested values. 1185 * 1186 * This method will always cache values in the range -128 to 127, 1187 * inclusive, and may cache other values outside of this range. 1188 * 1189 * @param l a long value. 1190 * @return a {@code Long} instance representing {@code l}. 1191 * @since 1.5 1192 */ 1193 @HotSpotIntrinsicCandidate 1194 public static Long valueOf(long l) { 1195 final int offset = 128; 1196 if (l >= -128 && l <= 127) { // will cache 1197 return LongCache.cache[(int)l + offset]; 1198 } 1199 return new Long(l); 1200 } 1201 1202 /** 1203 * Decodes a {@code String} into a {@code Long}. 1204 * Accepts decimal, hexadecimal, and octal numbers given by the 1205 * following grammar: 1206 * 1207 * <blockquote> 1208 * <dl> 1209 * <dt><i>DecodableString:</i> 1210 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1211 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1212 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1213 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1214 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1215 * 1216 * <dt><i>Sign:</i> 1217 * <dd>{@code -} 1218 * <dd>{@code +} 1219 * </dl> 1220 * </blockquote> 1221 * 1222 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1223 * are as defined in section 3.10.1 of 1224 * <cite>The Java™ Language Specification</cite>, 1225 * except that underscores are not accepted between digits. 1226 * 1227 * <p>The sequence of characters following an optional 1228 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1229 * "{@code #}", or leading zero) is parsed as by the {@code 1230 * Long.parseLong} method with the indicated radix (10, 16, or 8). 1231 * This sequence of characters must represent a positive value or 1232 * a {@link NumberFormatException} will be thrown. The result is 1233 * negated if first character of the specified {@code String} is 1234 * the minus sign. No whitespace characters are permitted in the 1235 * {@code String}. 1236 * 1237 * @param nm the {@code String} to decode. 1238 * @return a {@code Long} object holding the {@code long} 1239 * value represented by {@code nm} 1240 * @throws NumberFormatException if the {@code String} does not 1241 * contain a parsable {@code long}. 1242 * @see java.lang.Long#parseLong(String, int) 1243 * @since 1.2 1244 */ 1245 public static Long decode(String nm) throws NumberFormatException { 1246 int radix = 10; 1247 int index = 0; 1248 boolean negative = false; 1249 Long result; 1250 1251 if (nm.length() == 0) 1252 throw new NumberFormatException("Zero length string"); 1253 char firstChar = nm.charAt(0); 1254 // Handle sign, if present 1255 if (firstChar == '-') { 1256 negative = true; 1257 index++; 1258 } else if (firstChar == '+') 1259 index++; 1260 1261 // Handle radix specifier, if present 1262 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1263 index += 2; 1264 radix = 16; 1265 } 1266 else if (nm.startsWith("#", index)) { 1267 index ++; 1268 radix = 16; 1269 } 1270 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1271 index ++; 1272 radix = 8; 1273 } 1274 1275 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1276 throw new NumberFormatException("Sign character in wrong position"); 1277 1278 try { 1279 result = Long.valueOf(nm.substring(index), radix); 1280 result = negative ? Long.valueOf(-result.longValue()) : result; 1281 } catch (NumberFormatException e) { 1282 // If number is Long.MIN_VALUE, we'll end up here. The next line 1283 // handles this case, and causes any genuine format error to be 1284 // rethrown. 1285 String constant = negative ? ("-" + nm.substring(index)) 1286 : nm.substring(index); 1287 result = Long.valueOf(constant, radix); 1288 } 1289 return result; 1290 } 1291 1292 /** 1293 * The value of the {@code Long}. 1294 * 1295 * @serial 1296 */ 1297 private final long value; 1298 1299 /** 1300 * Constructs a newly allocated {@code Long} object that 1301 * represents the specified {@code long} argument. 1302 * 1303 * @param value the value to be represented by the 1304 * {@code Long} object. 1305 * 1306 * @deprecated 1307 * It is rarely appropriate to use this constructor. The static factory 1308 * {@link #valueOf(long)} is generally a better choice, as it is 1309 * likely to yield significantly better space and time performance. 1310 */ 1311 @Deprecated(since="9") 1312 public Long(long value) { 1313 this.value = value; 1314 } 1315 1316 /** 1317 * Constructs a newly allocated {@code Long} object that 1318 * represents the {@code long} value indicated by the 1319 * {@code String} parameter. The string is converted to a 1320 * {@code long} value in exactly the manner used by the 1321 * {@code parseLong} method for radix 10. 1322 * 1323 * @param s the {@code String} to be converted to a 1324 * {@code Long}. 1325 * @throws NumberFormatException if the {@code String} does not 1326 * contain a parsable {@code long}. 1327 * 1328 * @deprecated 1329 * It is rarely appropriate to use this constructor. 1330 * Use {@link #parseLong(String)} to convert a string to a 1331 * {@code long} primitive, or use {@link #valueOf(String)} 1332 * to convert a string to a {@code Long} object. 1333 */ 1334 @Deprecated(since="9") 1335 public Long(String s) throws NumberFormatException { 1336 this.value = parseLong(s, 10); 1337 } 1338 1339 /** 1340 * Returns the value of this {@code Long} as a {@code byte} after 1341 * a narrowing primitive conversion. 1342 * @jls 5.1.3 Narrowing Primitive Conversions 1343 */ 1344 public byte byteValue() { 1345 return (byte)value; 1346 } 1347 1348 /** 1349 * Returns the value of this {@code Long} as a {@code short} after 1350 * a narrowing primitive conversion. 1351 * @jls 5.1.3 Narrowing Primitive Conversions 1352 */ 1353 public short shortValue() { 1354 return (short)value; 1355 } 1356 1357 /** 1358 * Returns the value of this {@code Long} as an {@code int} after 1359 * a narrowing primitive conversion. 1360 * @jls 5.1.3 Narrowing Primitive Conversions 1361 */ 1362 public int intValue() { 1363 return (int)value; 1364 } 1365 1366 /** 1367 * Returns the value of this {@code Long} as a 1368 * {@code long} value. 1369 */ 1370 @HotSpotIntrinsicCandidate 1371 public long longValue() { 1372 return value; 1373 } 1374 1375 /** 1376 * Returns the value of this {@code Long} as a {@code float} after 1377 * a widening primitive conversion. 1378 * @jls 5.1.2 Widening Primitive Conversions 1379 */ 1380 public float floatValue() { 1381 return (float)value; 1382 } 1383 1384 /** 1385 * Returns the value of this {@code Long} as a {@code double} 1386 * after a widening primitive conversion. 1387 * @jls 5.1.2 Widening Primitive Conversions 1388 */ 1389 public double doubleValue() { 1390 return (double)value; 1391 } 1392 1393 /** 1394 * Returns a {@code String} object representing this 1395 * {@code Long}'s value. The value is converted to signed 1396 * decimal representation and returned as a string, exactly as if 1397 * the {@code long} value were given as an argument to the 1398 * {@link java.lang.Long#toString(long)} method. 1399 * 1400 * @return a string representation of the value of this object in 1401 * base 10. 1402 */ 1403 public String toString() { 1404 return toString(value); 1405 } 1406 1407 /** 1408 * Returns a hash code for this {@code Long}. The result is 1409 * the exclusive OR of the two halves of the primitive 1410 * {@code long} value held by this {@code Long} 1411 * object. That is, the hashcode is the value of the expression: 1412 * 1413 * <blockquote> 1414 * {@code (int)(this.longValue()^(this.longValue()>>>32))} 1415 * </blockquote> 1416 * 1417 * @return a hash code value for this object. 1418 */ 1419 @Override 1420 public int hashCode() { 1421 return Long.hashCode(value); 1422 } 1423 1424 /** 1425 * Returns a hash code for a {@code long} value; compatible with 1426 * {@code Long.hashCode()}. 1427 * 1428 * @param value the value to hash 1429 * @return a hash code value for a {@code long} value. 1430 * @since 1.8 1431 */ 1432 public static int hashCode(long value) { 1433 return (int)(value ^ (value >>> 32)); 1434 } 1435 1436 /** 1437 * Compares this object to the specified object. The result is 1438 * {@code true} if and only if the argument is not 1439 * {@code null} and is a {@code Long} object that 1440 * contains the same {@code long} value as this object. 1441 * 1442 * @param obj the object to compare with. 1443 * @return {@code true} if the objects are the same; 1444 * {@code false} otherwise. 1445 */ 1446 public boolean equals(Object obj) { 1447 if (obj instanceof Long) { 1448 return value == ((Long)obj).longValue(); 1449 } 1450 return false; 1451 } 1452 1453 /** 1454 * Determines the {@code long} value of the system property 1455 * with the specified name. 1456 * 1457 * <p>The first argument is treated as the name of a system 1458 * property. System properties are accessible through the {@link 1459 * java.lang.System#getProperty(java.lang.String)} method. The 1460 * string value of this property is then interpreted as a {@code 1461 * long} value using the grammar supported by {@link Long#decode decode} 1462 * and a {@code Long} object representing this value is returned. 1463 * 1464 * <p>If there is no property with the specified name, if the 1465 * specified name is empty or {@code null}, or if the property 1466 * does not have the correct numeric format, then {@code null} is 1467 * returned. 1468 * 1469 * <p>In other words, this method returns a {@code Long} object 1470 * equal to the value of: 1471 * 1472 * <blockquote> 1473 * {@code getLong(nm, null)} 1474 * </blockquote> 1475 * 1476 * @param nm property name. 1477 * @return the {@code Long} value of the property. 1478 * @throws SecurityException for the same reasons as 1479 * {@link System#getProperty(String) System.getProperty} 1480 * @see java.lang.System#getProperty(java.lang.String) 1481 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1482 */ 1483 public static Long getLong(String nm) { 1484 return getLong(nm, null); 1485 } 1486 1487 /** 1488 * Determines the {@code long} value of the system property 1489 * with the specified name. 1490 * 1491 * <p>The first argument is treated as the name of a system 1492 * property. System properties are accessible through the {@link 1493 * java.lang.System#getProperty(java.lang.String)} method. The 1494 * string value of this property is then interpreted as a {@code 1495 * long} value using the grammar supported by {@link Long#decode decode} 1496 * and a {@code Long} object representing this value is returned. 1497 * 1498 * <p>The second argument is the default value. A {@code Long} object 1499 * that represents the value of the second argument is returned if there 1500 * is no property of the specified name, if the property does not have 1501 * the correct numeric format, or if the specified name is empty or null. 1502 * 1503 * <p>In other words, this method returns a {@code Long} object equal 1504 * to the value of: 1505 * 1506 * <blockquote> 1507 * {@code getLong(nm, new Long(val))} 1508 * </blockquote> 1509 * 1510 * but in practice it may be implemented in a manner such as: 1511 * 1512 * <blockquote><pre> 1513 * Long result = getLong(nm, null); 1514 * return (result == null) ? new Long(val) : result; 1515 * </pre></blockquote> 1516 * 1517 * to avoid the unnecessary allocation of a {@code Long} object when 1518 * the default value is not needed. 1519 * 1520 * @param nm property name. 1521 * @param val default value. 1522 * @return the {@code Long} value of the property. 1523 * @throws SecurityException for the same reasons as 1524 * {@link System#getProperty(String) System.getProperty} 1525 * @see java.lang.System#getProperty(java.lang.String) 1526 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1527 */ 1528 public static Long getLong(String nm, long val) { 1529 Long result = Long.getLong(nm, null); 1530 return (result == null) ? Long.valueOf(val) : result; 1531 } 1532 1533 /** 1534 * Returns the {@code long} value of the system property with 1535 * the specified name. The first argument is treated as the name 1536 * of a system property. System properties are accessible through 1537 * the {@link java.lang.System#getProperty(java.lang.String)} 1538 * method. The string value of this property is then interpreted 1539 * as a {@code long} value, as per the 1540 * {@link Long#decode decode} method, and a {@code Long} object 1541 * representing this value is returned; in summary: 1542 * 1543 * <ul> 1544 * <li>If the property value begins with the two ASCII characters 1545 * {@code 0x} or the ASCII character {@code #}, not followed by 1546 * a minus sign, then the rest of it is parsed as a hexadecimal integer 1547 * exactly as for the method {@link #valueOf(java.lang.String, int)} 1548 * with radix 16. 1549 * <li>If the property value begins with the ASCII character 1550 * {@code 0} followed by another character, it is parsed as 1551 * an octal integer exactly as by the method {@link 1552 * #valueOf(java.lang.String, int)} with radix 8. 1553 * <li>Otherwise the property value is parsed as a decimal 1554 * integer exactly as by the method 1555 * {@link #valueOf(java.lang.String, int)} with radix 10. 1556 * </ul> 1557 * 1558 * <p>Note that, in every case, neither {@code L} 1559 * ({@code '\u005Cu004C'}) nor {@code l} 1560 * ({@code '\u005Cu006C'}) is permitted to appear at the end 1561 * of the property value as a type indicator, as would be 1562 * permitted in Java programming language source code. 1563 * 1564 * <p>The second argument is the default value. The default value is 1565 * returned if there is no property of the specified name, if the 1566 * property does not have the correct numeric format, or if the 1567 * specified name is empty or {@code null}. 1568 * 1569 * @param nm property name. 1570 * @param val default value. 1571 * @return the {@code Long} value of the property. 1572 * @throws SecurityException for the same reasons as 1573 * {@link System#getProperty(String) System.getProperty} 1574 * @see System#getProperty(java.lang.String) 1575 * @see System#getProperty(java.lang.String, java.lang.String) 1576 */ 1577 public static Long getLong(String nm, Long val) { 1578 String v = null; 1579 try { 1580 v = System.getProperty(nm); 1581 } catch (IllegalArgumentException | NullPointerException e) { 1582 } 1583 if (v != null) { 1584 try { 1585 return Long.decode(v); 1586 } catch (NumberFormatException e) { 1587 } 1588 } 1589 return val; 1590 } 1591 1592 /** 1593 * Compares two {@code Long} objects numerically. 1594 * 1595 * @param anotherLong the {@code Long} to be compared. 1596 * @return the value {@code 0} if this {@code Long} is 1597 * equal to the argument {@code Long}; a value less than 1598 * {@code 0} if this {@code Long} is numerically less 1599 * than the argument {@code Long}; and a value greater 1600 * than {@code 0} if this {@code Long} is numerically 1601 * greater than the argument {@code Long} (signed 1602 * comparison). 1603 * @since 1.2 1604 */ 1605 public int compareTo(Long anotherLong) { 1606 return compare(this.value, anotherLong.value); 1607 } 1608 1609 /** 1610 * Compares two {@code long} values numerically. 1611 * The value returned is identical to what would be returned by: 1612 * <pre> 1613 * Long.valueOf(x).compareTo(Long.valueOf(y)) 1614 * </pre> 1615 * 1616 * @param x the first {@code long} to compare 1617 * @param y the second {@code long} to compare 1618 * @return the value {@code 0} if {@code x == y}; 1619 * a value less than {@code 0} if {@code x < y}; and 1620 * a value greater than {@code 0} if {@code x > y} 1621 * @since 1.7 1622 */ 1623 public static int compare(long x, long y) { 1624 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1625 } 1626 1627 /** 1628 * Compares two {@code long} values numerically treating the values 1629 * as unsigned. 1630 * 1631 * @param x the first {@code long} to compare 1632 * @param y the second {@code long} to compare 1633 * @return the value {@code 0} if {@code x == y}; a value less 1634 * than {@code 0} if {@code x < y} as unsigned values; and 1635 * a value greater than {@code 0} if {@code x > y} as 1636 * unsigned values 1637 * @since 1.8 1638 */ 1639 public static int compareUnsigned(long x, long y) { 1640 return compare(x + MIN_VALUE, y + MIN_VALUE); 1641 } 1642 1643 1644 /** 1645 * Returns the unsigned quotient of dividing the first argument by 1646 * the second where each argument and the result is interpreted as 1647 * an unsigned value. 1648 * 1649 * <p>Note that in two's complement arithmetic, the three other 1650 * basic arithmetic operations of add, subtract, and multiply are 1651 * bit-wise identical if the two operands are regarded as both 1652 * being signed or both being unsigned. Therefore separate {@code 1653 * addUnsigned}, etc. methods are not provided. 1654 * 1655 * @param dividend the value to be divided 1656 * @param divisor the value doing the dividing 1657 * @return the unsigned quotient of the first argument divided by 1658 * the second argument 1659 * @see #remainderUnsigned 1660 * @since 1.8 1661 */ 1662 public static long divideUnsigned(long dividend, long divisor) { 1663 if (divisor < 0L) { // signed comparison 1664 // Answer must be 0 or 1 depending on relative magnitude 1665 // of dividend and divisor. 1666 return (compareUnsigned(dividend, divisor)) < 0 ? 0L :1L; 1667 } 1668 1669 if (dividend > 0) // Both inputs non-negative 1670 return dividend/divisor; 1671 else { 1672 /* 1673 * For simple code, leveraging BigInteger. Longer and faster 1674 * code written directly in terms of operations on longs is 1675 * possible; see "Hacker's Delight" for divide and remainder 1676 * algorithms. 1677 */ 1678 return toUnsignedBigInteger(dividend). 1679 divide(toUnsignedBigInteger(divisor)).longValue(); 1680 } 1681 } 1682 1683 /** 1684 * Returns the unsigned remainder from dividing the first argument 1685 * by the second where each argument and the result is interpreted 1686 * as an unsigned value. 1687 * 1688 * @param dividend the value to be divided 1689 * @param divisor the value doing the dividing 1690 * @return the unsigned remainder of the first argument divided by 1691 * the second argument 1692 * @see #divideUnsigned 1693 * @since 1.8 1694 */ 1695 public static long remainderUnsigned(long dividend, long divisor) { 1696 if (dividend > 0 && divisor > 0) { // signed comparisons 1697 return dividend % divisor; 1698 } else { 1699 if (compareUnsigned(dividend, divisor) < 0) // Avoid explicit check for 0 divisor 1700 return dividend; 1701 else 1702 return toUnsignedBigInteger(dividend). 1703 remainder(toUnsignedBigInteger(divisor)).longValue(); 1704 } 1705 } 1706 1707 // Bit Twiddling 1708 1709 /** 1710 * The number of bits used to represent a {@code long} value in two's 1711 * complement binary form. 1712 * 1713 * @since 1.5 1714 */ 1715 @Native public static final int SIZE = 64; 1716 1717 /** 1718 * The number of bytes used to represent a {@code long} value in two's 1719 * complement binary form. 1720 * 1721 * @since 1.8 1722 */ 1723 public static final int BYTES = SIZE / Byte.SIZE; 1724 1725 /** 1726 * Returns a {@code long} value with at most a single one-bit, in the 1727 * position of the highest-order ("leftmost") one-bit in the specified 1728 * {@code long} value. Returns zero if the specified value has no 1729 * one-bits in its two's complement binary representation, that is, if it 1730 * is equal to zero. 1731 * 1732 * @param i the value whose highest one bit is to be computed 1733 * @return a {@code long} value with a single one-bit, in the position 1734 * of the highest-order one-bit in the specified value, or zero if 1735 * the specified value is itself equal to zero. 1736 * @since 1.5 1737 */ 1738 public static long highestOneBit(long i) { 1739 return i & (MIN_VALUE >>> numberOfLeadingZeros(i)); 1740 } 1741 1742 /** 1743 * Returns a {@code long} value with at most a single one-bit, in the 1744 * position of the lowest-order ("rightmost") one-bit in the specified 1745 * {@code long} value. Returns zero if the specified value has no 1746 * one-bits in its two's complement binary representation, that is, if it 1747 * is equal to zero. 1748 * 1749 * @param i the value whose lowest one bit is to be computed 1750 * @return a {@code long} value with a single one-bit, in the position 1751 * of the lowest-order one-bit in the specified value, or zero if 1752 * the specified value is itself equal to zero. 1753 * @since 1.5 1754 */ 1755 public static long lowestOneBit(long i) { 1756 // HD, Section 2-1 1757 return i & -i; 1758 } 1759 1760 /** 1761 * Returns the number of zero bits preceding the highest-order 1762 * ("leftmost") one-bit in the two's complement binary representation 1763 * of the specified {@code long} value. Returns 64 if the 1764 * specified value has no one-bits in its two's complement representation, 1765 * in other words if it is equal to zero. 1766 * 1767 * <p>Note that this method is closely related to the logarithm base 2. 1768 * For all positive {@code long} values x: 1769 * <ul> 1770 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)} 1771 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)} 1772 * </ul> 1773 * 1774 * @param i the value whose number of leading zeros is to be computed 1775 * @return the number of zero bits preceding the highest-order 1776 * ("leftmost") one-bit in the two's complement binary representation 1777 * of the specified {@code long} value, or 64 if the value 1778 * is equal to zero. 1779 * @since 1.5 1780 */ 1781 @HotSpotIntrinsicCandidate 1782 public static int numberOfLeadingZeros(long i) { 1783 int x = (int)(i >>> 32); 1784 return x == 0 ? 32 + Integer.numberOfLeadingZeros((int)i) 1785 : Integer.numberOfLeadingZeros(x); 1786 } 1787 1788 /** 1789 * Returns the number of zero bits following the lowest-order ("rightmost") 1790 * one-bit in the two's complement binary representation of the specified 1791 * {@code long} value. Returns 64 if the specified value has no 1792 * one-bits in its two's complement representation, in other words if it is 1793 * equal to zero. 1794 * 1795 * @param i the value whose number of trailing zeros is to be computed 1796 * @return the number of zero bits following the lowest-order ("rightmost") 1797 * one-bit in the two's complement binary representation of the 1798 * specified {@code long} value, or 64 if the value is equal 1799 * to zero. 1800 * @since 1.5 1801 */ 1802 @HotSpotIntrinsicCandidate 1803 public static int numberOfTrailingZeros(long i) { 1804 int x = (int)i; 1805 return x == 0 ? 32 + Integer.numberOfTrailingZeros((int)(i >>> 32)) 1806 : Integer.numberOfTrailingZeros(x); 1807 } 1808 1809 /** 1810 * Returns the number of one-bits in the two's complement binary 1811 * representation of the specified {@code long} value. This function is 1812 * sometimes referred to as the <i>population count</i>. 1813 * 1814 * @param i the value whose bits are to be counted 1815 * @return the number of one-bits in the two's complement binary 1816 * representation of the specified {@code long} value. 1817 * @since 1.5 1818 */ 1819 @HotSpotIntrinsicCandidate 1820 public static int bitCount(long i) { 1821 // HD, Figure 5-2 1822 i = i - ((i >>> 1) & 0x5555555555555555L); 1823 i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); 1824 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; 1825 i = i + (i >>> 8); 1826 i = i + (i >>> 16); 1827 i = i + (i >>> 32); 1828 return (int)i & 0x7f; 1829 } 1830 1831 /** 1832 * Returns the value obtained by rotating the two's complement binary 1833 * representation of the specified {@code long} value left by the 1834 * specified number of bits. (Bits shifted out of the left hand, or 1835 * high-order, side reenter on the right, or low-order.) 1836 * 1837 * <p>Note that left rotation with a negative distance is equivalent to 1838 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1839 * distance)}. Note also that rotation by any multiple of 64 is a 1840 * no-op, so all but the last six bits of the rotation distance can be 1841 * ignored, even if the distance is negative: {@code rotateLeft(val, 1842 * distance) == rotateLeft(val, distance & 0x3F)}. 1843 * 1844 * @param i the value whose bits are to be rotated left 1845 * @param distance the number of bit positions to rotate left 1846 * @return the value obtained by rotating the two's complement binary 1847 * representation of the specified {@code long} value left by the 1848 * specified number of bits. 1849 * @since 1.5 1850 */ 1851 public static long rotateLeft(long i, int distance) { 1852 return (i << distance) | (i >>> -distance); 1853 } 1854 1855 /** 1856 * Returns the value obtained by rotating the two's complement binary 1857 * representation of the specified {@code long} value right by the 1858 * specified number of bits. (Bits shifted out of the right hand, or 1859 * low-order, side reenter on the left, or high-order.) 1860 * 1861 * <p>Note that right rotation with a negative distance is equivalent to 1862 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1863 * distance)}. Note also that rotation by any multiple of 64 is a 1864 * no-op, so all but the last six bits of the rotation distance can be 1865 * ignored, even if the distance is negative: {@code rotateRight(val, 1866 * distance) == rotateRight(val, distance & 0x3F)}. 1867 * 1868 * @param i the value whose bits are to be rotated right 1869 * @param distance the number of bit positions to rotate right 1870 * @return the value obtained by rotating the two's complement binary 1871 * representation of the specified {@code long} value right by the 1872 * specified number of bits. 1873 * @since 1.5 1874 */ 1875 public static long rotateRight(long i, int distance) { 1876 return (i >>> distance) | (i << -distance); 1877 } 1878 1879 /** 1880 * Returns the value obtained by reversing the order of the bits in the 1881 * two's complement binary representation of the specified {@code long} 1882 * value. 1883 * 1884 * @param i the value to be reversed 1885 * @return the value obtained by reversing order of the bits in the 1886 * specified {@code long} value. 1887 * @since 1.5 1888 */ 1889 public static long reverse(long i) { 1890 // HD, Figure 7-1 1891 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; 1892 i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; 1893 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; 1894 1895 return reverseBytes(i); 1896 } 1897 1898 /** 1899 * Returns the signum function of the specified {@code long} value. (The 1900 * return value is -1 if the specified value is negative; 0 if the 1901 * specified value is zero; and 1 if the specified value is positive.) 1902 * 1903 * @param i the value whose signum is to be computed 1904 * @return the signum function of the specified {@code long} value. 1905 * @since 1.5 1906 */ 1907 public static int signum(long i) { 1908 // HD, Section 2-7 1909 return (int) ((i >> 63) | (-i >>> 63)); 1910 } 1911 1912 /** 1913 * Returns the value obtained by reversing the order of the bytes in the 1914 * two's complement representation of the specified {@code long} value. 1915 * 1916 * @param i the value whose bytes are to be reversed 1917 * @return the value obtained by reversing the bytes in the specified 1918 * {@code long} value. 1919 * @since 1.5 1920 */ 1921 @HotSpotIntrinsicCandidate 1922 public static long reverseBytes(long i) { 1923 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; 1924 return (i << 48) | ((i & 0xffff0000L) << 16) | 1925 ((i >>> 16) & 0xffff0000L) | (i >>> 48); 1926 } 1927 1928 /** 1929 * Adds two {@code long} values together as per the + operator. 1930 * 1931 * @param a the first operand 1932 * @param b the second operand 1933 * @return the sum of {@code a} and {@code b} 1934 * @see java.util.function.BinaryOperator 1935 * @since 1.8 1936 */ 1937 public static long sum(long a, long b) { 1938 return a + b; 1939 } 1940 1941 /** 1942 * Returns the greater of two {@code long} values 1943 * as if by calling {@link Math#max(long, long) Math.max}. 1944 * 1945 * @param a the first operand 1946 * @param b the second operand 1947 * @return the greater of {@code a} and {@code b} 1948 * @see java.util.function.BinaryOperator 1949 * @since 1.8 1950 */ 1951 public static long max(long a, long b) { 1952 return Math.max(a, b); 1953 } 1954 1955 /** 1956 * Returns the smaller of two {@code long} values 1957 * as if by calling {@link Math#min(long, long) Math.min}. 1958 * 1959 * @param a the first operand 1960 * @param b the second operand 1961 * @return the smaller of {@code a} and {@code b} 1962 * @see java.util.function.BinaryOperator 1963 * @since 1.8 1964 */ 1965 public static long min(long a, long b) { 1966 return Math.min(a, b); 1967 } 1968 1969 /** 1970 * Returns a nominal descriptor for this instance, which is the instance 1971 * itself. 1972 * 1973 * @return an {@link Optional} describing the {@linkplain Long} instance 1974 * @since 12 1975 */ 1976 @Override 1977 public Optional<Long> describeConstable() { 1978 return Optional.of(this); 1979 } 1980 1981 /** 1982 * Resolves this instance as a {@link ConstantDesc}, the result of which is 1983 * the instance itself. 1984 * 1985 * @param lookup ignored 1986 * @return the {@linkplain Long} instance 1987 * @since 12 1988 */ 1989 @Override 1990 public Long resolveConstantDesc(MethodHandles.Lookup lookup) { 1991 return this; 1992 } 1993 1994 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1995 @Native private static final long serialVersionUID = 4290774380558885855L; 1996 }