0

I am looking for a more efficient way to perform the following action, where I am appending the return value of a method to an array. However if the return is null i want to perform another action and not change the array.

Object[] myVal = new Object[10];
Object temp;
temp = myFunction();
if(temp != null) {
    myVal[count++] = temp;
} else {
    System.Exit();
}

Where I want to assign a variable to the return of a method, but provide an 'inline' check to carry out another action if the value returned is null.

Something like:

myVal = (myFunction() != null) ? [output of expression]: System.Exit();

Is there any method like this?

3
  • What's inefficient about your current code? Commented Mar 13, 2013 at 21:05
  • At least the new Object part. Commented Mar 13, 2013 at 21:05
  • I'm looking to try an avoid creating an instance of the temp Object Commented Mar 13, 2013 at 21:22

2 Answers 2

6
myVal = myFunction();
if (myVal == null) System.exit(0);

No need for a temp variable.

Sign up to request clarification or add additional context in comments.

2 Comments

I think the OP wants to avoid the variable assignment when the method returns null. Of course, if he's actually doing System.exit(0) it won't matter.
@GriffeyDog "Avoid the assignment?" Doesn't that mean to keep it assigned to null, which he is trying to avoid anyway?
0

Try this:

if ((myVal = myFunction()) == null) System.exit(0);
else // do your work

Note: Usage of ternary operators is not recommended because code becomes hard to read.

2 Comments

if myVal was an array that i am adding the return value onto the end of, would this add the null value? i ideally want to check for the value before i would add it onto the end of the array.
Normally use temp instead of myVal...if ((temp = myFunction()) != null) myVal[index] = temp;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.