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