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

NullPointerException in ternary operator

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 7u72, 8u25, 8u40
    • core-libs
    • x86_64
    • windows_7

      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);

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

              Created:
              Updated:
              Resolved: