< prev index next >

src/java.base/share/classes/java/lang/Integer.java

Print this page

   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.AOTRuntimeSetup;
  32 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
  33 import jdk.internal.vm.annotation.ForceInline;
  34 import jdk.internal.vm.annotation.IntrinsicCandidate;
  35 import jdk.internal.vm.annotation.Stable;
  36 
  37 import java.lang.annotation.Native;
  38 import java.lang.constant.Constable;
  39 import java.lang.constant.ConstantDesc;
  40 import java.lang.invoke.MethodHandles;
  41 import java.util.Objects;
  42 import java.util.Optional;
  43 
  44 import static java.lang.Character.digit;
  45 import static java.lang.String.COMPACT_STRINGS;
  46 
  47 /**
  48  * The {@code Integer} class is the {@linkplain
  49  * java.lang##wrapperClass wrapper class} for values of the primitive
  50  * type {@code int}. An object of type {@code Integer} contains a
  51  * single field whose type is {@code int}.
  52  *
  53  * <p>In addition, this class provides several methods for converting
  54  * an {@code int} to a {@code String} and a {@code String} to an
  55  * {@code int}, as well as other constants and methods useful when
  56  * dealing with an {@code int}.
  57  *
  58  * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
  59  * class; programmers should treat instances that are
  60  * {@linkplain #equals(Object) equal} as interchangeable and should not
  61  * use instances for synchronization, or unpredictable behavior may
  62  * occur. For example, in a future release, synchronization may fail.








  63  *
  64  * <p>Implementation note: The implementations of the "bit twiddling"
  65  * methods (such as {@link #highestOneBit(int) highestOneBit} and
  66  * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
  67  * based on material from Henry S. Warren, Jr.'s <cite>Hacker's
  68  * Delight</cite>, (Addison Wesley, 2002) and <cite>Hacker's
  69  * Delight, Second Edition</cite>, (Pearson Education, 2013).
  70  *
  71  * @since 1.0
  72  */
  73 @jdk.internal.ValueBased
  74 public final class Integer extends Number

  75         implements Comparable<Integer>, Constable, ConstantDesc {
  76     /**
  77      * A constant holding the minimum value an {@code int} can
  78      * have, -2<sup>31</sup>.
  79      */
  80     @Native public static final int   MIN_VALUE = 0x80000000;
  81 
  82     /**
  83      * A constant holding the maximum value an {@code int} can
  84      * have, 2<sup>31</sup>-1.
  85      */
  86     @Native public static final int   MAX_VALUE = 0x7fffffff;
  87 
  88     /**
  89      * The {@code Class} instance representing the primitive type
  90      * {@code int}.
  91      *
  92      * @since   1.1
  93      */
  94     public static final Class<Integer> TYPE = Class.getPrimitiveClass("int");

 863      * object equal to the value of:
 864      *
 865      * <blockquote>
 866      *  {@code Integer.valueOf(Integer.parseInt(s))}
 867      * </blockquote>
 868      *
 869      * @param      s   the string to be parsed.
 870      * @return     an {@code Integer} object holding the value
 871      *             represented by the string argument.
 872      * @throws     NumberFormatException  if the string cannot be parsed
 873      *             as an integer.
 874      */
 875     public static Integer valueOf(String s) throws NumberFormatException {
 876         return Integer.valueOf(parseInt(s, 10));
 877     }
 878 
 879     /**
 880      * Cache to support the object identity semantics of autoboxing for values between
 881      * -128 and 127 (inclusive) as required by JLS.
 882      *




 883      * The cache is initialized on first usage.  The size of the cache
 884      * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
 885      * During VM initialization, java.lang.Integer.IntegerCache.high property
 886      * may be set and saved in the private system properties in the
 887      * jdk.internal.misc.VM class.
 888      *
 889      * WARNING: The cache is archived with CDS and reloaded from the shared
 890      * archive at runtime. The archived cache (Integer[]) and Integer objects
 891      * reside in the closed archive heap regions. Care should be taken when
 892      * changing the implementation and the cache array should not be assigned
 893      * with new Integer object(s) after initialization.
 894      */
 895 
 896     @AOTSafeClassInitializer
 897     private static final class IntegerCache {
 898         static final int low = -128;
 899         @Stable static int high;
 900 
 901         @Stable static Integer[] cache;
 902         static Integer[] archivedCache;

 905             runtimeSetup();
 906         }
 907 
 908         @AOTRuntimeSetup
 909         private static void runtimeSetup() {
 910             // high value may be configured by property
 911             int h = 127;
 912             String integerCacheHighPropValue =
 913                 VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
 914             if (integerCacheHighPropValue != null) {
 915                 try {
 916                     h = Math.max(parseInt(integerCacheHighPropValue), 127);
 917                     // Maximum array size is Integer.MAX_VALUE
 918                     h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
 919                 } catch( NumberFormatException nfe) {
 920                     // If the property cannot be parsed into an int, ignore it.
 921                 }
 922             }
 923             high = h;
 924 
 925             Integer[] precomputed = null;
 926             if (cache != null) {
 927                 // IntegerCache has been AOT-initialized.
 928                 precomputed = cache;
 929             } else {
 930                 // Legacy CDS archive support (to be deprecated):
 931                 // Load IntegerCache.archivedCache from archive, if possible
 932                 CDS.initializeFromArchive(IntegerCache.class);
 933                 precomputed = archivedCache;
 934             }
 935 
 936             cache = loadOrInitializeCache(precomputed);
 937             archivedCache = cache; // Legacy CDS archive support (to be deprecated)
 938             // range [-128, 127] must be interned (JLS7 5.1.7)
 939             assert IntegerCache.high >= 127;
 940         }
 941 
 942         private static Integer[] loadOrInitializeCache(Integer[] precomputed) {
 943             int size = (high - low) + 1;
 944 
 945             // Use the precomputed cache if it exists and is large enough
 946             if (precomputed != null && size <= precomputed.length) {
 947                 return precomputed;
 948             }
 949 
 950             Integer[] c = new Integer[size];
 951             int j = low;
 952             // If we loading a precomputed cache (from AOT cache or CDS archive),
 953             // we must use all instances from it.
 954             // Otherwise, the Integers from the AOT cache (or CDS archive) will not
 955             // have the same object identity as items in IntegerCache.cache[].
 956             int precomputedSize = (precomputed == null) ? 0 : precomputed.length;
 957             for (int i = 0; i < precomputedSize; i++) {
 958                 c[i] = precomputed[i];
 959                 assert j == precomputed[i];
 960                 j++;
 961             }
 962             // Fill the rest of the cache.
 963             for (int i = precomputedSize; i < size; i++) {
 964                 c[i] = new Integer(j++);
 965             }
 966             return c;
 967         }
 968 








 969         private IntegerCache() {}
 970     }
 971 
 972     /**
 973      * Returns an {@code Integer} instance representing the specified
 974      * {@code int} value.  If a new {@code Integer} instance is not
 975      * required, this method should generally be used in preference to
 976      * the constructor {@link #Integer(int)}, as this method is likely
 977      * to yield significantly better space and time performance by
 978      * caching frequently requested values.
 979      *
 980      * This method will always cache values in the range -128 to 127,
 981      * inclusive, and may cache other values outside of this range.












 982      *
 983      * @param  i an {@code int} value.
 984      * @return an {@code Integer} instance representing {@code i}.
 985      * @since  1.5
 986      */
 987     @IntrinsicCandidate
 988     public static Integer valueOf(int i) {
 989         if (i >= IntegerCache.low && i <= IntegerCache.high)
 990             return IntegerCache.cache[i + (-IntegerCache.low)];
 991         return new Integer(i);
 992     }
 993 
 994     /**
 995      * The value of the {@code Integer}.
 996      *
 997      * @serial
 998      */
 999     private final int value;
1000 
1001     /**
1002      * Constructs a newly allocated {@code Integer} object that
1003      * represents the specified {@code int} value.
1004      *
1005      * @param   value   the value to be represented by the
1006      *                  {@code Integer} object.
1007      *
1008      * @deprecated
1009      * It is rarely appropriate to use this constructor. The static factory
1010      * {@link #valueOf(int)} is generally a better choice, as it is
1011      * likely to yield significantly better space and time performance.
1012      */
1013     @Deprecated(since="9")

1014     public Integer(int value) {
1015         this.value = value;
1016     }
1017 
1018     /**
1019      * Constructs a newly allocated {@code Integer} object that
1020      * represents the {@code int} value indicated by the
1021      * {@code String} parameter. The string is converted to an
1022      * {@code int} value in exactly the manner used by the
1023      * {@code parseInt} method for radix 10.
1024      *
1025      * @param   s   the {@code String} to be converted to an {@code Integer}.
1026      * @throws      NumberFormatException if the {@code String} does not
1027      *              contain a parsable integer.
1028      *
1029      * @deprecated
1030      * It is rarely appropriate to use this constructor.
1031      * Use {@link #parseInt(String)} to convert a string to a
1032      * {@code int} primitive, or use {@link #valueOf(String)}
1033      * to convert a string to an {@code Integer} object.

   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.Deserializer;
  33 import jdk.internal.value.ValueClass;
  34 import jdk.internal.vm.annotation.AOTRuntimeSetup;
  35 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
  36 import jdk.internal.vm.annotation.ForceInline;
  37 import jdk.internal.vm.annotation.IntrinsicCandidate;
  38 import jdk.internal.vm.annotation.Stable;
  39 
  40 import java.lang.annotation.Native;
  41 import java.lang.constant.Constable;
  42 import java.lang.constant.ConstantDesc;
  43 import java.lang.invoke.MethodHandles;
  44 import java.util.Objects;
  45 import java.util.Optional;
  46 
  47 import static java.lang.Character.digit;
  48 import static java.lang.String.COMPACT_STRINGS;
  49 
  50 /**
  51  * The {@code Integer} class is the {@linkplain
  52  * java.lang##wrapperClass wrapper class} for values of the primitive
  53  * type {@code int}. An object of type {@code Integer} contains a
  54  * single field whose type is {@code int}.
  55  *
  56  * <p>In addition, this class provides several methods for converting
  57  * an {@code int} to a {@code String} and a {@code String} to an
  58  * {@code int}, as well as other constants and methods useful when
  59  * dealing with an {@code int}.
  60  *
  61  * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
  62  * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
  63  * as interchangeable and should not use instances for synchronization or
  64  * with {@linkplain java.lang.ref.Reference object references}.
  65  *
  66  * <div class="preview-block">
  67  *      <div class="preview-comment">
  68  *          When preview features are enabled, {@code Integer} is a {@linkplain Class#isValue value class}.
  69  *          Use of value class instances for synchronization or with
  70  *          {@linkplain java.lang.ref.Reference object references} result in
  71  *          {@link IdentityException}.
  72  *      </div>
  73  * </div>
  74  *
  75  * <p>Implementation note: The implementations of the "bit twiddling"
  76  * methods (such as {@link #highestOneBit(int) highestOneBit} and
  77  * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
  78  * based on material from Henry S. Warren, Jr.'s <cite>Hacker's
  79  * Delight</cite>, (Addison Wesley, 2002) and <cite>Hacker's
  80  * Delight, Second Edition</cite>, (Pearson Education, 2013).
  81  *
  82  * @since 1.0
  83  */
  84 @jdk.internal.ValueBased
  85 // See doc/value-class-preview.md for an overview of value class generation
  86 public final /*value*/ class Integer extends Number
  87         implements Comparable<Integer>, Constable, ConstantDesc {
  88     /**
  89      * A constant holding the minimum value an {@code int} can
  90      * have, -2<sup>31</sup>.
  91      */
  92     @Native public static final int   MIN_VALUE = 0x80000000;
  93 
  94     /**
  95      * A constant holding the maximum value an {@code int} can
  96      * have, 2<sup>31</sup>-1.
  97      */
  98     @Native public static final int   MAX_VALUE = 0x7fffffff;
  99 
 100     /**
 101      * The {@code Class} instance representing the primitive type
 102      * {@code int}.
 103      *
 104      * @since   1.1
 105      */
 106     public static final Class<Integer> TYPE = Class.getPrimitiveClass("int");

 875      * object equal to the value of:
 876      *
 877      * <blockquote>
 878      *  {@code Integer.valueOf(Integer.parseInt(s))}
 879      * </blockquote>
 880      *
 881      * @param      s   the string to be parsed.
 882      * @return     an {@code Integer} object holding the value
 883      *             represented by the string argument.
 884      * @throws     NumberFormatException  if the string cannot be parsed
 885      *             as an integer.
 886      */
 887     public static Integer valueOf(String s) throws NumberFormatException {
 888         return Integer.valueOf(parseInt(s, 10));
 889     }
 890 
 891     /**
 892      * Cache to support the object identity semantics of autoboxing for values between
 893      * -128 and 127 (inclusive) as required by JLS.
 894      *
 895      * When preview features are enabled, the cache does not affect object
 896      * equality {@code ==} semantics, but exists for performance.
 897      * See doc/value-class-preview.md "Wrapper Class Caches" section.
 898      *
 899      * The cache is initialized on first usage.  The size of the cache
 900      * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
 901      * During VM initialization, java.lang.Integer.IntegerCache.high property
 902      * may be set and saved in the private system properties in the
 903      * jdk.internal.misc.VM class.
 904      *
 905      * WARNING: The cache is archived with CDS and reloaded from the shared
 906      * archive at runtime. The archived cache (Integer[]) and Integer objects
 907      * reside in the closed archive heap regions. Care should be taken when
 908      * changing the implementation and the cache array should not be assigned
 909      * with new Integer object(s) after initialization.
 910      */
 911 
 912     @AOTSafeClassInitializer
 913     private static final class IntegerCache {
 914         static final int low = -128;
 915         @Stable static int high;
 916 
 917         @Stable static Integer[] cache;
 918         static Integer[] archivedCache;

 921             runtimeSetup();
 922         }
 923 
 924         @AOTRuntimeSetup
 925         private static void runtimeSetup() {
 926             // high value may be configured by property
 927             int h = 127;
 928             String integerCacheHighPropValue =
 929                 VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
 930             if (integerCacheHighPropValue != null) {
 931                 try {
 932                     h = Math.max(parseInt(integerCacheHighPropValue), 127);
 933                     // Maximum array size is Integer.MAX_VALUE
 934                     h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
 935                 } catch( NumberFormatException nfe) {
 936                     // If the property cannot be parsed into an int, ignore it.
 937                 }
 938             }
 939             high = h;
 940 
 941             Integer[] precomputed;
 942             if (cache != null) {
 943                 // IntegerCache has been AOT-initialized.
 944                 precomputed = cache;
 945             } else {
 946                 // Legacy CDS archive support (to be deprecated):
 947                 // Load IntegerCache.archivedCache from archive, if possible
 948                 CDS.initializeFromArchive(IntegerCache.class);
 949                 precomputed = archivedCache;
 950             }
 951 
 952             cache = loadOrInitializeCache(precomputed);
 953             archivedCache = cache; // Legacy CDS archive support (to be deprecated)
 954             // range [-128, 127] must be interned (JLS7 5.1.7)
 955             assert IntegerCache.high >= 127;
 956         }
 957 
 958         private static Integer[] loadOrInitializeCache(Integer[] precomputed) {
 959             int size = (high - low) + 1;
 960 
 961             // Use the precomputed cache if it exists and is large enough
 962             if (precomputed != null && size <= precomputed.length) {
 963                 return precomputed;
 964             }
 965 
 966             Integer[] c = newCacheArray(size);
 967             int j = low;
 968             // If we loading a precomputed cache (from AOT cache or CDS archive),
 969             // we must use all instances from it.
 970             // Otherwise, the Integers from the AOT cache (or CDS archive) will not
 971             // have the same object identity as items in IntegerCache.cache[].
 972             int precomputedSize = (precomputed == null) ? 0 : precomputed.length;
 973             for (int i = 0; i < precomputedSize; i++) {
 974                 c[i] = precomputed[i];
 975                 assert j == precomputed[i];
 976                 j++;
 977             }
 978             // Fill the rest of the cache.
 979             for (int i = precomputedSize; i < size; i++) {
 980                 c[i] = new Integer(j++);
 981             }
 982             return c;
 983         }
 984 
 985         private static Integer[] newCacheArray(int size) {
 986             // ValueClass.newReferenceArray requires a value class component.
 987             if (PreviewFeatures.isEnabled()) {
 988                 return (Integer[]) ValueClass.newReferenceArray(Integer.class, size);
 989             }
 990             return new Integer[size];
 991         }
 992 
 993         private IntegerCache() {}
 994     }
 995 
 996     /**
 997      * Returns an {@code Integer} instance representing the specified
 998      * {@code int} value.
 999      * <div class="preview-block">
1000      *      <div class="preview-comment">
1001      *          <p>
1002      *              - When preview features are NOT enabled, {@code Integer} is an identity class.
1003      *              If a new {@code Integer} instance is not
1004      *              required, this method should generally be used in preference to
1005      *              the constructor {@link #Integer(int)}, as this method is likely
1006      *              to yield significantly better space and time performance by
1007      *              caching frequently requested values.
1008      *              This method will always cache values in the range -128 to 127,
1009      *              inclusive, and may cache other values outside of this range.
1010      *          </p>
1011      *          <p>
1012      *              - When preview features are enabled, {@code Integer} is a {@linkplain Class#isValue value class}.
1013      *              The {@code valueOf} behavior is the same as invoking the constructor,
1014      *              whether cached or not.
1015      *          </p>
1016      *      </div>
1017      * </div>
1018      *
1019      * @param  i an {@code int} value.
1020      * @return an {@code Integer} instance representing {@code i}.
1021      * @since  1.5
1022      */
1023     @IntrinsicCandidate
1024     public static Integer valueOf(int i) {
1025         if (i >= IntegerCache.low && i <= IntegerCache.high)
1026             return IntegerCache.cache[i + (-IntegerCache.low)];
1027         return new Integer(i);
1028     }
1029 
1030     /**
1031      * The value of the {@code Integer}.
1032      *
1033      * @serial
1034      */
1035     private final int value;
1036 
1037     /**
1038      * Constructs a newly allocated {@code Integer} object that
1039      * represents the specified {@code int} value.
1040      *
1041      * @param   value   the value to be represented by the
1042      *                  {@code Integer} object.
1043      *
1044      * @deprecated
1045      * It is rarely appropriate to use this constructor. The static factory
1046      * {@link #valueOf(int)} is generally a better choice, as it is
1047      * likely to yield significantly better space and time performance.
1048      */
1049     @Deprecated(since="9")
1050     @Deserializer("value")
1051     public Integer(int value) {
1052         this.value = value;
1053     }
1054 
1055     /**
1056      * Constructs a newly allocated {@code Integer} object that
1057      * represents the {@code int} value indicated by the
1058      * {@code String} parameter. The string is converted to an
1059      * {@code int} value in exactly the manner used by the
1060      * {@code parseInt} method for radix 10.
1061      *
1062      * @param   s   the {@code String} to be converted to an {@code Integer}.
1063      * @throws      NumberFormatException if the {@code String} does not
1064      *              contain a parsable integer.
1065      *
1066      * @deprecated
1067      * It is rarely appropriate to use this constructor.
1068      * Use {@link #parseInt(String)} to convert a string to a
1069      * {@code int} primitive, or use {@link #valueOf(String)}
1070      * to convert a string to an {@code Integer} object.
< prev index next >