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

JSType.toNarrowestNumber never returns Integer

    Details

      Description

      FULL PRODUCT VERSION :
      9

      A DESCRIPTION OF THE PROBLEM :
      http://book2s.com/java/src/package/jdk/nashorn/internal/runtime/jstype.html#1f2ca1218bfe8fd34d4b40a8fba83acc

          /**
           * Convert a long to the narrowest JavaScript Number type. This returns either a
           * {@link Integer} or {@link Double} depending on the magnitude of {@code l}.
           * @param l a long value
           * @return the value converted to Integer or Double
           */
          public static Number toNarrowestNumber(final long l) {
              return isRepresentableAsInt(l) ? Integer.valueOf((int) l) : Double
                      .valueOf(l);
          }


      Because of the unboxing rules for numeric conditional expressions (https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.25.2), the operands here will be unboxed and widened to doubles, and thus the result will be boxed back to Double. As such, Integer isn't returned.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      https://ideone.com/Opw18m

          public static Number toNarrowestNumber(boolean condition, final long l) {
              return condition ? Integer.valueOf((int) l) : Double
                      .valueOf(l);
          }
       
      public static void main (String[] args) throws java.lang.Exception
      {
      System.out.println(toNarrowestNumber(true, 0).getClass());
      System.out.println(toNarrowestNumber(false, 0).getClass());
      }

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      class java.lang.Integer
      class java.lang.Double
      ACTUAL -
      class java.lang.Double
      class java.lang.Double

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------

      class Ideone
      {
          public static Number toNarrowestNumber(boolean condition, final long l) {
              return condition ? Integer.valueOf((int) l) : Double
                      .valueOf(l);
          }
       
      public static void main (String[] args) throws java.lang.Exception
      {
      System.out.println(toNarrowestNumber(true, 0).getClass());
      System.out.println(toNarrowestNumber(false, 0).getClass());
      }
      }
      ---------- END SOURCE ----------

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                pmuthuswamy Priya Lakshmi Muthuswamy (Inactive)
                Reporter:
                webbuggrp Webbug Group
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: