Simple and best way to solve Null pointer exception at this line:
oS = ((SyIntBVO)syIntBVOList.get(0)).getSource().trim();
Exception on getSource variable. how to add null check?
Simple and best way to solve Null pointer exception at this line:
oS = ((SyIntBVO)syIntBVOList.get(0)).getSource().trim();
Exception on getSource variable. how to add null check?
String oS = ((SyIntBVO)syIntBVOList.get(0)).getSource();
if(os != null) {
os = oS.trim(); // we're good
} else {
// deal with null
}
Or, if get(0)
returns null, this will work:
SyIntBVO syIntBvo = ((SyIntBVO)syIntBVOList.get(0));
if(syIntBvo != null) {
String os = SyIntBvo.getSource().trim(); // we're good
} else {
// deal with null
}
To decide which one you need we require more details, e.g. a stack trace.
Depending on how "defensive" you need your code to be, technically you could need to check for null
on anything that potentially could be null
. At the extreme case, this is any object you de-reference. For example...
Can syIntBVOList
be null
? Then you need to check it before you de-reference it:
if (syIntBVOList == null) {
return;
}
SomeType variable = syIntBVOList.get(0);
Can variable
be null
? Can its casted version be null
?
SyIntBVO anotherVariable = ((SyIntBVO)variable);
if (anotherVariable == null) {
return;
}
Can getSource()
return null
? Same pattern. And so on...
It's really up to your code what can or can not potentially be null
. If any of these instances of an object, whether stored in a variable or referenced directly in-line, can be null
then you would want to check for that null
reference before de-referencing it.
(Note: It's often considered an anti-pattern for a method which should return an instance to sometimes return null
. For exactly this reason, because it requires consuming code to be this defensive.)