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