Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8065614 JEP 277: Enhanced Deprecation
  3. JDK-8176335

Release Note: Deprecation of Boxed Primitive Constructors



    • Verified


      Classes `Boolean`, `Byte`, `Short`, `Character`, `Integer`, `Long`, `Float`, and `Double` are "box" classes that correspond to primitive types. The constructors of these classes have been deprecated.

      Given a value of the corresponding primitive type, it is generally unnecessary to construct new instances of these box classes. The recommended alternatives to construction are autoboxing or the `valueOf` static factory methods. In most cases, autoboxing will work, so an expression whose type is a primitive can be used in locations where a box class is required. This is covered in the *Java Language Specification*, section 5.1.7, "Boxing Conversion." For example, given `List<Integer> intList`, the code to add an `Integer` might be as follows:
          intList.add(new Integer(347));
      This can be replaced with:
      Autoboxing should not be used in places where it might affect overload resolution. For example, there are two overloads of the `List.remove` method:
          List.remove(int i) // removes the element at index i
          List.remove(Object obj) // removes an element equal to obj
      The code to remove the `Integer` value 347 might be as follows:
          intList.remove(new Integer(347));
      If this code is changed in an attempt to use autoboxing:
      This will not remove the `Integer` value 347, but instead it will resolve to the other overloaded method, and it will attempt to remove the element at index 347.

      Autoboxing cannot be used in such cases. Instead, code should be changed to use the `valueOf` static factory method:

      Autoboxing is preferable from a readability standpoint, but a safer transformation is to replace calls to the box constructors with calls to the `valueOf` static factory method.

      Using autoboxing or the `valueOf` method reduces memory footprint compared to the constructors, as the integral box types will generally cache and reuse instances corresponding to small values. The special case of `Boolean` has static fields for the two cached instances, namely `Boolean.FALSE` and `Boolean.TRUE`.

      With the exception of `Character`, the box classes also have constructors that take a `String` argument. These parse and convert the string value and return a new instance of the box class. A `valueOf` overload taking a `String` is the equivalent static factory method for this constructor. Usually it's preferable to call one of the `parse` methods (`Integer.parseInt`, `Double.parseDouble`, etc.) which convert the string and return primitive values instead of boxed instances.


        Issue Links



              smarks Stuart Marks
              smarks Stuart Marks
              0 Vote for this issue
              1 Start watching this issue