Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly write a null test on input that is nullable to avoid warnings in Java?

How to write a proper test on a method that can return a null to assign the value to a nonnull variable?

@Nonnull String abc;
if(holderForState.getNodeElementSelectedAPI() == null || holderForState.getNodeElementSelectedAPI().equals("")) {
    throw new IllegalArgumentException("SelectedAPI is empty or null during logic usage");
}
abc = holderForState.getNodeElementSelectedAPI();

Why does VS-code tell me that: Null type safety: The expression of type ‘String’ needs unchecked conversion to conform to ‘@Nonnull String’Java(16778128) on abc assignment line? I am literally testing if it is null 1 line above and throwing out of context if it is…

I tried multiple versions of this test, but I get the same. To make it simpler I am showing the assignment, whereas in reality I am using abc as a method parameter, with same outcomes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are always calling the .getNodeElementSelectedAPI(); method. It might be the case that the return type of this methods is different after the second call so it can possible get null.

I would recommend you to write your code something like

String abc = holderForState.getNodeElementSelectedAPI();
if( abc == null || abc.equals("")) {
    throw new IllegalArgumentException("SelectedAPI is empty or null during logic usage");
}

The variable abc can get null but it would still trigger the IllegalArgumentException.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading