tim_xyz tim_xyz - 3 months ago 12
Android Question

Why is creating then separately returning `int[] arrayName = {};` redundant? (Java)

I'm getting a

Local variable 'answerArray' is redundant
warning on the following code:

int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};
return answerArray;


Full method:

public int[] answerArray (int answer) {
Random randomGenerator = new Random();
int fakeFirstAnswer = randomGenerator.nextInt(10);
int fakeSecondAnswer = randomGenerator.nextInt(10);

int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};
return answerArray;
}


I've tried refactoring like below but then it errors with an
expects ;
.

return int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};


Can anyone recommend a syntax? I'm just getting started with Java/Android.

Answer

In Java, for array variable declarations,

int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};

is shorthand for

int[] answerArray = new int[] {answer, fakeFirstAnswer, fakeSecondAnswer};
//                  ^-- the Java compiler does this

However, return is not a variable declaration and needs the explicit new int[] syntax, as pointed out by Sotirios

return new int[] {answer, fakeFirstAnswer, fakeSecondAnswer};

(In both cases Java will automatically determine the length of the array.)

Comments