Check if Object has data or not? - java

I am calling method to get data as per passed text that will ping into database.
So I want to check if there is data arrived in object or not.
Code :
Method m = service.getMethodDataByFilter(text);
I have tried :
if(m == null){
System.out.println("In NULL");
}
but it does not entering inside it.
I have also tried :
if(m.getName().isEmpty()){
System.out.println("In NULL");
}
then it throws NPE in condition because no data received.
So how to check if there is data inside object or not ?
Method Class :
public class Method {
private Integer id;
private String name;
// getter-setter
}
UPDATE
Have just try Ruchira
if(m== null){
System.out.println("m is null");
}else if(m.getName()==null){
System.out.println("m.getName() is null");
}else if(m.getName().isEmpty()){
System.out.println("m.getName() is empty");
}
Still throws same NPE.
FULL Method Code :
public MethodDTO getMethod(String text){
Method m = service.getMethod(text);
if(m == null){
System.out.println("m is null");
}else if(m.getName()==null){
System.out.println("m.getName() is null");
}else if(m.getName().isEmpty()){
System.out.println("m.getName() is empty");
}
ModelMapper mapper = ModelMap.methodMapper();
return mapper.map(m, MethodDTO.class);
}

Try this if ( m == null || m.getName()== null). Note that apart from m its name may also be null.

You need to change your code to :
if(myObject==null){ // check if object is null
System.out.println("myObject is NULL");
}
else{ // myObject should not be null here
if(myObject.getField1()==null) // check for fields within the object
{
System.out.println("field1 is NULL");
}
if(myObject.getField2()==null)
{
System.out.println("field2 is NULL");
}
...
}
Note if the object is null, then trying to access any non-static field / method on it will result in NPE.

Explanation.
if(m == null){
System.out.println("In NULL");
}
Since inside if not enter since m is not null. But
if(m.getName().isEmpty()){
System.out.println("In NULL");
}
Here you get NullPointerException since m.getName() is null.
So you can try as follows
if(m == null){
System.out.println("m is null");
}else if(m.getName()==null){
System.out.println("m.getName() is null");
}else if(m.getName().isEmpty()){
System.out.println("m.getName() is empty");
}

m == null
will return false when object m is not null but it does not check all its attributes recursively inside object.
m.getName()
seems to be returning null but even this statement will not throw NPE. But yes if you call m.getName().isEmpty() will throw NPE. You should better check like this:
if (m.getName() == null) //assuming you have already checked for m being null

Check the object is null or not like this:
if(m != null && m.getName != null) {
// Object m is not null and m.getName is also not null
} else {
// Either Object m is null or m.getName is null or both are null
}

Related

How to handle empty response from DB?

I am fetching value from db in dbval variable. So I want to add condition, pass the case if the value equals "apple" or the value is empty or null. But if the value is diff like "orange" or "mango", throw error.
My code:
if (StringUtils.equals(apple, dbval) || dbval.equalsIgnoreCase(null) || dbval.isEmpty())
{
dbValueFlag = true;
logger.info("DB value matched ",);
}
else
{
logger.info("DB valuenot matched for pnac");
}
You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.
Example:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Or
if(str != null && !str.isEmpty()) { /* do your stuffs here */ }
Add throws InvalidArgumentException to your method signature. And throw this exception from the else block in your code.
public void thisIsYourMethod(String dbVal) throws InvalidArgumentException {
if (StringUtils.equals(apple, dbval) || dbval.equalsIgnoreCase(null) || dbval.isEmpty()) {
dbValueFlag = true;
logger.info("DB value matched ",);
} else {
logger.info("DB valuenot matched for pnac");
throw new InvalidArgumentException("Argument Passed in Wrong");
}
}

Introduce a new variable instead of reusing the parameter "entity"

I am solving SonarQube issues , in that issues I face an below warning any one please tell me how can i fix it,
Here is my class
public static Agency updateEntity(AgencyModel model, Agency entity) {
if (model == null || entity == null) {
return null;
}
if (entity.getAgencyId() != model.getAgencyId()) {
entity = new Agency()
// for the above variable 'entity' i get the warning, "Introduce a new
variable instead of reusing the parameter "entity".
}
entity.setAgencyId(model.getAgencyId());
if (entity.getAgencyLogoLarge() == null) {
entity.setAgencyLogoLarge(new File());
}
entity.setAgencyLogoLarge(FileModel.updateEntity(model.getAgencyLogoLarge(), entity.getAgencyLogoLarge()));
if (entity.getAgencyLogoSmall() == null) {
entity.setAgencyLogoSmall(new File());
}
entity.setAgencyLogoSmall(FileModel.updateEntity(model.getAgencyLogoSmall(), entity.getAgencyLogoSmall()));
entity.setAgencyName(model.getAgencyName());
entity.setContactPersons(
AgencyContactPersonModel.updateEntities(model.getContactPersons(), entity.getContactPersons()));
entity.setOtherDetails(model.getOtherDetails());
entity.setClassification(ClassificationModel.updateEntity(model.getClassification(), entity.getClassification()));
entity.setStatus(entity.getStatus());
entity.setCreatedBy((model.getCreatedBy() != null && model.getCreatedBy() != 0) ? model.getCreatedBy()
: entity.getCreatedBy());
entity.setUpdatedBy((model.getUpdatedBy() != null && model.getUpdatedBy() != 0) ? model.getUpdatedBy()
: entity.getUpdatedBy());
entity.setUpdatedDate(new Date());
entity.setStatus(Constant.ACTIVE);
return entity;
}
In above method i get that warning , will any one please tell me that what is the best approach to solve the above problem.
Assigning a value to a method argument often indicates a bug (even though this is not the case in your example), which is probably why SonarQube gives that warning.
Assuming you have no way of disabling that warning (or you don't want to), you can eliminate it by introducing a new local variable:
public static Agency updateEntity(AgencyModel model, Agency entity) {
Entity result;
if (model == null || entity == null) {
return null;
}
if (entity.getAgencyId() != model.getAgencyId()) {
result = new Agency();
} else {
result = entity;
}
... use result variable instead of entity variable ...
return result;
}

java for loop that runs list executes only once

The for loop in the code below only executes once. I was looking at similiar questions but those have something that breaks it like editing the list in the loop while I dont.
public String getProfileList(JSONObject obj, String uuid) {
JSONObject profile = (JSONObject) obj.get("profiles");
#SuppressWarnings("unchecked")
ArrayList<String> list = new ArrayList<String>(profile.keySet());
System.out.println(list);
for (String object: list) {
System.out.println(object);
String isUUID = (String) ((JSONObject) profile.get(object)).get("mpm-data:uuid");
System.out.println(object + " == " + isUUID);
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}
}
System.out.println("no profile found.");
return null;
}
This code outputs this:
[5fb4acd48e7d422eabecd82e32fb03c6, 44d01181eae635d31f2cefe5e1f75cd4,e0e96e422659dfdc1ad16d53a37ee618, a3ae7136f900457290e99bd657db0385]
5fb4acd48e7d422eabecd82e32fb03c6
5fb4acd48e7d422eabecd82e32fb03c6 == null
For your console output you can see that isUUID is null. This means that when you attempt to call its method equals there is actually no object to call it to and you should be getting a NullPointerException. That's why it is best to do equals assertions with the part you know will not be null on the left side:
uuid.equals(isUUID) would be better.
Notice that if you do an equals assertion with a variable and a static string then it is best to do it like so:
"myCompareString".equals(myVariable), since "myCompareString" can never be null whereas myVariable can.
if (isUUID.equals(uuid)) will throw a nullPointerException when isuuid is null.
You should check if the data is right, and handle the exception.
And you can use StringUtils.equals(String str1, String str2) in commons-lang.jar, then you don't need to handle the null yourself, see http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
System.out.println(object + " == " + isUUID);
Code prints
5fb4acd48e7d422eabecd82e32fb03c6 == null and next statement you are using in if condition .If isUUID is null it should throw null pointer exception.Can you please check this point
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}

How to handle a method where the parameter is tightly connected to the return value. What if the parameter is null? Java

I'm writing a method that should return the first item in an array belonging to a certain user. The class looks like this:
public MailItem getNextMailItem(String who)
{
return mailbox.get(who).pollFirst();
}
I need some sort of error handling in case the "who"-parameter is empty or null e.g
if (who != null && who.length() != 0)
But what if that turns out to be false?
your if block is something like that
public MailItem getNextMailItem(String who) {
MailItem item = null;
if (who != null && who.length() != 0) {
item = mailbox.get(who).pollFirst();
} else {
//show some error message or error log here
}
return item;
}
on filure your method will return null.
also read this Q&A
Returning null in the absence of a value would be an obvious solution:
public MailItem getNextMailItem(String who){
MailItem mailItem = null;
if (who != null && who.length() != 0){
mailItem = mailbox.get(who).pollFirst();
}
return mailItem;
}
But consider this:
If you communicate with null, your return value really is ambiguous. It can mean a lot of things. Instead, you could use Guava's Optional or the Null object pattern.
Using the Null pattern, you would define an instance that has a neutral behavior, possibly in your MailItem interface, and return it in case of the absence of a value:
public MailItem getNextMailItem(String who) {
MailItem mailItem = null;
if (who != null && who.length() != 0){
mailbox.get(who).pollFirst();
} else {
mailItem = MailItem.NULL_ITEM;
}
return mailItem;
}
This way - unless an unexpected exception happens - you can always be sure that getNextMailItem returns a valid instance of MailItem.
Simple solution is to return null. On the other side, check for null and handle accordingly.

handling Null for bigdecimal

My code looks like below,
caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
if(caseXObj != null && caseXObj.getCaseInGrossAmt() != null){
} else {
caseXObj.setCaseAmt(BigDecimal.ZERO);
}
I have handled NUll pointer for the caseX and also for getter and when null set the bigdeciaml to a default ZERO value. Still I get Null pointer exception in the setter line.Any suggestions?
It's quite possible that caseXObj is null, so it'll cause the NullPointerException. You should test the three cases like this:
caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
if (caseXObj != null && caseXObj.getCaseInGrossAmt() != null) {
// do something with caseXObj
} else if (caseXObj == null) {
// initialize caseXObj, you were misssing this case!
} else {
caseXObj.setCaseAmt(BigDecimal.ZERO);
}
In essence, the error was that you were testing for only two cases - and there are three of them.
Assuming it is OK for getCaseXDao() to return null, you need to assign to caseXObj rather than use it as a pointer in the else clause.
That because you don't check for null in your else part.
It should be:
caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
if(caseXObj != null && caseXObj.getCaseInGrossAmt() != null)
{
//...
}
else
{
if (caseXObj != null)
{
caseXObj.setCaseAmt(BigDecimal.ZERO);
}
}

Categories

Resources