Search code examples
javaarraysreturn

How to return a temporary int array in Java


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?


Solution

  • 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.