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