I have a scenario where I need to check for null
. I have a key named dT
:
String dT = (String) caseChk.get("dT");
This throws a NullPointerException
, since that key itself doesn't exist. If I check with
if(caseChk.get("dT") != null) {
// do something
}
yet another NullPointerException
is thrown because of .get
. How can I test for null
when a key in the map doesn't exist? I understand that the put
method should handle it, but that isn't under my control.]
Even now I get nullpoiner since .get throws exception
If caseChk.get("dT")
is only line you have there and sure it is throwing exception, then only possibility is caseChk
could be null.
To make sure key exists you should use HashMap#containsKey(key)
function. Once key exists you may use HashMap#get(key)
to get the value and compare it to null.
caseChk coud be null try this
String dT;
if(chaseChk!= null)
dT= (String)caseChk.get("dT");`
Try this using the method to check null
public String checkNull_HashMap(Hashtable hashMap, String hashKey) {
if (hashMap.get(hashKey) == null) {
return "";
} else {
return hashMap.get(hashKey).toString();
}
}
The best option is to check for null before calling toString()
if ( hashMap.get(hashKey) != null ) { return hashMap.get(hashKey).toString(); }
Try this, this will work.
if(!caseChk.isEmpty)
{
String dT = (caseChk.containsKey("dT")?(String)caseChk.get("dT"):" ")
}