-5

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());
Karthikeyan
  • 1,927
  • 6
  • 44
  • 109

2 Answers2

0

The nullpointer exception basic reason is that you are calling a method or variable from null variable where with null variable I mean a variable which is currently not holding reference of any object. So, the easy way to avoid it is assign that variable a refernce on which subsequent tasks can be called

Now this can be handled in n no. of ways, out of which some basic ways are:

1) Using if condition

if(doc!=null && sourceAsMap!=null && sourceAsMap.get("catalog_title")!=null)
doc.setCatalog_title(sourceAsMap.get("catalog_title").toString());

2) 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);

Hope that helps

Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
0

You can use Guava Preconditions (https://github.com/google/guava/wiki/PreconditionsExplained), as it good practice to check preconditions of your class before executing it. As you can use checkNotNull(T).

If you are expecting null in your system then instead of using a null check, use Optional class https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html,

If you are using Java 7 then you can use Optional from Guava https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

Hemant Singh
  • 1,487
  • 10
  • 15