0
//'main' method must be in a class 'Rextester'.
//openjdk version '11.0.5' 

import java.util.*;
import java.lang.*;

class Rextester
{  
    public static void main(String args[])
    {
        Integer a = null, b = null;
        Integer c = a != null && b != null ? Math.min(a,b) : (a != null ? a : (b != null ? b : null));
    }
}

I am completely baffled as to how this is returning a null pointer exception. Integer typesa && b are both set to null. c should return null, but a null pointer exception is thrown.

This does not occur when a and b are set to arbitrary values. This means the second ternary operation is failing (a != null ? a : (b != null ? b : null));

What is the reason behind this? Is there something I am missing.

camrydash
  • 93
  • 6
  • 1
    Because you have set `a` and `b` to the `null` and you are later doing `Math.min(null, null)` – Nitin Bisht Jun 09 '20 at 17:43
  • 2
    @NitinBisht Wrong, since `Math.min()` is only called when both are not null, so it's never called with null values. – Andreas Jun 09 '20 at 17:45
  • 4
    It is because the latter part of the expression needs to unbox the Integer to evaluate properly. And it is trying to unbox(i.e. dereference) a null object. – WJS Jun 09 '20 at 17:47
  • Have you tried `(a != null && b != null)` (using brackets)? – Mario MG Jun 09 '20 at 17:48
  • 2
    @MarioMG That shouldn't be a problem here - conditional operators have very low precedence – user Jun 09 '20 at 17:49
  • 4
    Check the duplicate links up top. The issue is that `Math.min()` returns an `int`, triggering the outer ternary operator to be `int`, not `Integer`, i.e. the statement compiles to `c = Integer.valueOf(a != null && b != null ? Math.min(a.intValue(), b.intValue()) : (a != null ? a : (b != null ? b : null)).intValue())`. It is the unboxing `intValue()` call at the end that causes NPE when both `a` and `b` are null. – Andreas Jun 09 '20 at 17:52
  • @Andreas you are right that's why I used later word in my statement and in this context Math.min() won't be executed because both are null. – Nitin Bisht Jun 09 '20 at 17:55
  • 1
    @NitinBisht Which means that `Math.min()` isn't called when `a` or `b` is null, neother earlier or later, and hence your comment is wrong. – Andreas Jun 09 '20 at 17:57
  • 1
    @Andreas is right, as casting `Math.min(a,b)` to `Integer` makes the code work (I just tried it out of curiosity) – Mario MG Jun 09 '20 at 18:03
  • 1
    @Andreas You are correct. I casted Math.min to Integer, and it is not throwing exception. Usually Visual Studio warns me about this, but since switching to Java, I forgot. +1 – camrydash Jun 09 '20 at 18:04

0 Answers0