Am using Bean class to get/set value for the attributes. In some cases am gettig Exception in thread "main" java.lang.NullPointerException
error due to the value is null. What will be the best practice to handle null pointer exception when we get/set values from/to bean class.
Is that ternary operator is good to use or any other suggestions?
Please find the below line of code where am getting null pointer exception.
doc.setCatalog_title(sourceAsMap.get("catalog_title").toString());
The null pointer exception basic cause is that you are calling a method or variable from null variable i.e. a variable which is currently not holding reference of any object. So, the easy way to avoid it is assign that variable a reference on which subsequent tasks can be called
Now this can be handled in n no. of ways, out of which some basic ways are:
Using if condition
if(doc!=null && sourceAsMap!=null && sourceAsMap.get("catalog_title")!=null)
doc.setCatalog_title(sourceAsMap.get("catalog_title").toString());
Using ternary operator:
doc = null == doc ? new Document():doc;
doc.setCatalog_title(sourceAsMap!=null && sourceAsMap.get("catalog_title")!=null ? sourceAsMap.get("catalog_title").toString() : null);