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

NullPointerException in ternary operator

    Details

    • Type: Bug
    • Status: Closed
    • Priority: P4
    • Resolution: Not an Issue
    • Affects Version/s: 7u72, 8u25, 8u40
    • Fix Version/s: None
    • Component/s: core-libs
    • Subcomponent:
    • CPU:
      x86_64
    • OS:
      windows_7

      Description

      FULL PRODUCT VERSION :
      1.7.0_72

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows [Version 6.1.7601]

      A DESCRIPTION OF THE PROBLEM :
      I'm trying to execute such code:

      public class Test {
          Double getDouble(){
              return null;
          }
          
          int getCount(){
              return 1;
          }
          
          void test(){
              Double value = 0.0;
              value = getCount() == 1 ? getDouble() : 1.0;
              System.out.println(value);
          }
          
          public static void main(String[] args) {
              new Test().test();
          }
      }

      and getting NullPointerException.
      The problem is in " value = getCount() == 1 ? getDouble() : 1.0;" line.
      Also if I change getDouble() to null everything works and this is strange.
      As I understand JVM cast everything to one type and during this cast NullPointerException occurs

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Run code:

      public class Test {
          Double getDouble(){
              return null;
          }
          
          int getCount(){
              return 1;
          }
          
          void test(){
              Double value = 0.0;
              value = getCount() == 1 ? getDouble() : 1.0;
              System.out.println(value);
          }
          
          public static void main(String[] args) {
              new Test().test();
          }
      }


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      To have "null" printed in console.
      ACTUAL -
      NullPointerException occurs

      REPRODUCIBILITY :
      This bug can be reproduced always.

      CUSTOMER SUBMITTED WORKAROUND :
      As a workaround I used regular if-else statement:

      Double value = 1.0;
      if (getCount() == 1){
           value = getCount();
      }
      System.out.println(value);

        Attachments

          Activity

            People

            • Assignee:
              darcy Joe Darcy
              Reporter:
              webbuggrp Webbug Group
            • Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: