7

How can I manage to return a temporary array in Java (in order to save code line, without creating a variable).

When doing initiation, I can use

int[] ret = {0,1};

While when doing return, I cannot use

return {0,1};

Do I miss something or is there a force typ-cast to do this?

I got the idea to use new int[] as the answers below. While, what's the reason the we don't need new int[] when doing initiation?

2
  • See the Java Language Spec for details. Commented Feb 29, 2016 at 15:35
  • 2
    You don't need to write the answer into your question. Just accept the answer which solved your question, that's all. Commented Feb 29, 2016 at 16:10

4 Answers 4

10

I got the idea to use new int[] as the answers below. While, what's the reason the we don't need new int[] when doing initiation?

When you write int[] ret = {0,1};, it is essentially a shortcut of writing int[] ret = new int[]{0,1};. From the doc:

Alternatively, you can use the shortcut syntax to create and initialize an array:

int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

Now when you return you have to explicitly write return new int[]{0,1}; because you are not doing an assignment operation(create and initialize as per the doc) to the array and hence you cannot use the shortcut. You will have to create an object using new.

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

1 Comment

Thanks for your detailed answer!
9

You can do something known as returning an anonymous array (as it has no name).

Do

return new int[] {0, 1};

for that...

Comments

6
   public int [] return check(){
       return new int[] {5,8,3,6,4};
     }

Comments

4

You can do something likewise,

return new int[]{1,2,3};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.