0
String var_a = null;
String var_b = null;


Xyz obj1 = new Xyz();
Abc obj2 = new Abc();


    if(var_a != null){
    obj1.setValue1(var_a);
    }

    if(var_b != null){
    obj1.setvalue2(var_b);
    }


    if(obj1 != null ){
    obj2.setvalue(obj1);
    }

In this case there is only 2 values but i may have 30 values to set on obj1.Problem is when i Initialize obj1 it assigns null to all its value and when i check if obj1 != null it reads obj1 as not null because by default value is assigned to them. I need something which can set obj1 value null not its reference but its value or something which can check all the value of obj1 if all are null and if any value is not null to it can be set on obj2. Thanks in advance

1
  • Your question is quite unclear. Are you saying that you want to check if any property of obj1is null, and then assign a value to those properties? Commented Jul 11, 2014 at 5:59

1 Answer 1

1

Your question is hard to understand. But if you mean you have 20 (as an example) values and you want to check if they are != null without typing it for every single one you can group them into a List and loop over it.

You do:

ArrayList<int> myIntegers = new ArrayList<>();
ArrayList<String> myStrings = new ArrayList<>();

// Add the values to the lists

// Perform null check
for( String value : myStrings)
{
    if(value != null)
    {
        // do your stuff here
    }
}

Same logic to any other data type.

1
  • This is probably the most convenient way to achieve this behavior. You got my upvote. Commented Jul 11, 2014 at 7:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.