JDK-8236521 : NullPointerException occurs when using conditional operator with a int and a Map
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 11.0.5
  • Priority: P3
  • Status: Closed
  • Resolution: Not an Issue
  • OS: generic
  • CPU: x86_64
  • Submitted: 2019-12-24
  • Updated: 2025-06-20
  • Resolved: 2020-07-01
Related Reports
Duplicate :  
Description
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



Comments
Looks like there was a regression in Java 8 where the null value from map.get was incorrectly assigned to the variable, likely pushing an NPE to occur later on when the variable is accessed. There are some surprising interactions with primitives and boxing when using the ternary operator. A quick search of the issue tracker will show this comes up regularly (e.g. search for "ternary null"). In this case, see JLS 15.25 (https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25). The resulting type of the ternary expression is int and unboxing of the second operand is performed (the result from map.get).
02-01-2020

Assigning to Stuart for now. Please re-assign if needed.
24-12-2019

The null is returned from Map.get methd on java8 but NullPointerException occurs on java11. Also on linux machine, the same problem occurred.
24-12-2019