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