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

NullPointerException occurs when using conditional operator with a int and a Map

XMLWordPrintable

    • x86_64
    • generic

      A DESCRIPTION OF THE PROBLEM :
      I implemented a conditional operator to assign a Integer value.
      It's first value was int and next value was Map having Integer values.
      This code didn't occur NullPointerException when the null returned from Map.get methd on java8, but occured NullPointerException on java11.

      REGRESSION : Last worked in version 8u231

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      1. define a Map<String, Integer> and initialize to HashMap.
      2. assign a Integer value using conditional operator with first value is int and next value is Map object above.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      NullPointerException don't occur at line on "Map.get".
      ACTUAL -
      NullPointerException occurs at line on "Map.get".

      ---------- BEGIN SOURCE ----------
      public class Main {
          public static void main(String args[]) throws Exception {
              boolean flg = false;
              Map<String, Integer> map = new HashMap<>();
              try {
                  Integer r = flg ? 0 : map.get("key");
                  System.out.println(r);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              
          }
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Using Map.getOrDefault method insted of Map.get to avoid null value.

      FREQUENCY : always


            psandoz Paul Sandoz
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: