Init null array problem:

Hello All,

I just ran into something I hadn't seen before, I have a String[] that is:

String[] someArr = getSomeValuesMethod();

If the getSomeValuesMethod() returns null, then how do I populate the array with a pre-determined value, like a message?

The only thing I could get to work was to create an if block condition that if the array was null, then create a new String[] and initialize it with a message in the first field.

Any other ideas?

Thanks,

James

[508 byte] By [jamesEstona] at [2007-11-27 5:56:09]
# 1

> Hello All,

> I just ran into something I hadn't seen before, I

> have a String[] that is:

> String[] someArr = getSomeValuesMethod();

> If the getSomeValuesMethod() returns null, then how

> do I populate the array with a pre-determined value,

> like a message?

>

> The only thing I could get to work was to create an

> if block condition that if the array was null, then

> create a new String[] and initialize it with a

> message in the first field.

>

> Any other ideas?

>

> Thanks,

> James

That's right, do something like this:

String[] someArr = getSomeValuesMethod();

if (someArr == null) {

someArr = <whatever your default value is>;

}

hunter9000a at 2007-7-12 16:26:13 > top of Java-index,Java Essentials,New To Java...
# 2
This was a simple one, I got it:String[] someArr = getSomeValuesMethod();someArr = new String[] {msg};I just didn't see it the first few times through.Thx.
jamesEstona at 2007-7-12 16:26:13 > top of Java-index,Java Essentials,New To Java...
# 3

> This was a simple one, I got it:

> String[] someArr = getSomeValuesMethod();

> someArr = new String[] {msg};

>

> I just didn't see it the first few times through.

>

> Thx.

What's the point of assigning someArr on the first line if you're just going to reassign it to something else on the second?

hunter9000a at 2007-7-12 16:26:13 > top of Java-index,Java Essentials,New To Java...
# 4
Sometimes the array will be null and other times it will not. It has to be discovered dynamically using the if block.
jamesEstona at 2007-7-12 16:26:13 > top of Java-index,Java Essentials,New To Java...
# 5

> Sometimes the array will be null and other times it

> will not. It has to be discovered dynamically using

> the if block.

Riiight, but in reply 2 you gave code that always overwrites the value returned from getSomeValuesMethod(), not just when it's null. What's your question?

hunter9000a at 2007-7-12 16:26:13 > top of Java-index,Java Essentials,New To Java...
# 6
He doesn't have a question, just a lack of understanding.
floundera at 2007-7-12 16:26:13 > top of Java-index,Java Essentials,New To Java...
# 7
... still waiting for the other shoe to drop...
Hippolytea at 2007-7-12 16:26:13 > top of Java-index,Java Essentials,New To Java...