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

Function returning a doubly-bool-negated value usually returns a wrong result

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Duplicate
    • Icon: P4 P4
    • None
    • 9.0.1
    • core-libs

      FULL PRODUCT VERSION :
      java version "9.0.1"
      Java(TM) SE Runtime Environment (build 9.0.1+11)
      Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

      (The same on various builds of 1.8.)

      ADDITIONAL OS VERSION INFORMATION :
      Mac OS High Sierra, but tried also on various versions of Windows

      A DESCRIPTION OF THE PROBLEM :
      When, within Nashorn, a javascript function is invoked that returns a doubly-bool-negated (e.g. !!(x) ) value, the resulting value is false when argument of double negation is an integer not equal to -1, 0, or 1. The code below ("Source code ...") demonstrares this with a value of 2.

      (I need to stress that one of the installations of Java on my Mac OS machine works correctly, but I cannot reproduce that correct result anywhere else.)

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Run the main method below, or run the following javascript code within nashorn, possibly using jjs utility:

      function boolNegate(x) { return !(x); }
      function boolDoublyNegate(x) { return !!(x); }
      print(boolNegate(-2));
      print(boolDoublyNegate(-2));
      print(!!(-2));

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      A printout of:
      false
      true
      true
      ACTUAL -
      A printout of:
      false
      false
      true

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
          public static void main(String[] args) throws Exception {
              new jdk.nashorn.api.scripting.NashornScriptEngineFactory().getScriptEngine().eval(
                      "function boolNegate(x) { return !(x); }\n" +
                              "function boolDoublyNegate(x) { return !!(x); }\n" +
                              "\n" +
                              "print(boolNegate(2));\n" +
                              "print(boolDoublyNegate(2));\n" +
                              "print(!!(2));");
          }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Replacing !!(...) with Boolean(...) works. That can be, however, nearly impossible when the code is third-party provided, possibly at runtime.

            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: