Java conditional operator ?: result type

后端 未结 5 1265
忘了有多久
忘了有多久 2020-11-27 17:38

I\'m a bit puzzled about the conditional operator. Consider the following two lines:

Float f1 = false? 1.0f: null;
Float f2 = false? 1.0f: false? 1.0f: null;         


        
5条回答
  •  时光取名叫无心
    2020-11-27 17:58

    I think rewriting the code makes the explanation clearer:

        float f = 1.0f;
    
        Float null_Float  = false?        f  : null;       // float + null  -> OK
        Float null_Float2 = false? (Float)f  : null_Float; // Float + Float -> OK
        Float npe         = false?        f  : null_Float; // float + Float -> NPE
    

    Thus the NPE is when we try to do something like:

    Float npe = false? 1.0f : (Float)null;
    

提交回复
热议问题