Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8240345

Ternary operator cause unnecessary unboxing

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 8, 11, 13
    • tools

      ADDITIONAL SYSTEM INFORMATION :
      1.8.0_242-b08
      11.0.6+10
      13.0.2+8

      A DESCRIPTION OF THE PROBLEM :
      Using ternary operator cause unnecessary unboxing comparing to regular if-else

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      public class Reboxing {

          public static Integer getIntegerReboxing(Number number) {
              return number instanceof Integer ? (Integer) number : number.intValue();
          }

          public static Integer getInteger(Number number) {
              if (number instanceof Integer) {
                  return (Integer) number;
              } else {
                  return number.intValue();
              }
          }

          public static void main(String[] args) {
              System.out.println(getIntegerReboxing(Integer.valueOf(1)));
              System.out.println(getInteger(Integer.valueOf(1)));
          }
      }


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      ternary operator should return Integer object as is and apply Integer.valueOf only for second case
      ACTUAL -
      JD-GUI:

      public class Reboxing
      {
        public static Integer getIntegerReboxing(Number number) { return Integer.valueOf((number instanceof Integer) ? ((Integer)number).intValue() : number.intValue()); }

        
        public static Integer getInteger(Number number) {
          if (number instanceof Integer) {
            return (Integer)number;
          }
          return Integer.valueOf(number.intValue());
        }

        
        public static void main(String[] args) {
          System.out.println(getIntegerReboxing(Integer.valueOf(1)));
          System.out.println(getInteger(Integer.valueOf(1)));
        }
      }

      CUSTOMER SUBMITTED WORKAROUND :
      manual boxing:
      ... : Integer.valueOf(number.intValue());

      FREQUENCY : always


            smarks Stuart Marks
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: