Community
Participate
Working Groups
Null reference analyzer raises a false positive for the following code, saying that element value can't be null in line after negative instanceof public void aa(Object element) { if( !(element instanceof String) || element == null) { // <-- false positive return; } System.err.println(element); }
Let's assume element is null. Then (element instanceof String) yields false, and (!(element instanceof String)) evaluates to true. The conditional or short-circuit rule hence kicks in, and the second part does not get evaluated. I believe so that the 'element cannot be null' warning of the compiler is right. Entered regression test NullReferenceTest #95.
Thanks Maxime. It is a false alarm indeed. Sorry about it. Though it would be interesting for the future to detect or suggest shorcircuitting. For example null analyzer could raise a warning for the following code where first comparison to null is redundant. if(element == null || !(element instanceof String)) { return; }
(In reply to comment #2) You're welcome. Regarding this other example, please feel free to file a separate bug. I can see one reason why some people would not use the suggested warning though: the complete coding of the test appears to be 2-3 times faster than the simpler and semantically equivalent !(element instanceof String) when the population is biased towards a majority of null values (admitted, I made a quick test on a single platform, with a 100% null population - but the results are still striking). Such a warning would to some extent promote code conciseness over performance, which I would prefer to avoid. Not that I'd want to promote the complete expression either, especially when the programmer knows that he gets rare nulls (or even none).
*** Bug 198967 has been marked as a duplicate of this bug. ***