-1

Is there any difference between

int[] numbers = new int [] {1,2,3,4,5};

and

int[] numbers = {1,2,3,4,5};

or do they express the same?

Which one shall be used?

4
  • use the second one - it's shorter ;) Commented May 11, 2018 at 8:53
  • They are exactly the same. Use whichever you find clearer. Commented May 11, 2018 at 8:53
  • 2
    @Logan Not exactly. The new int[] {...} must be used when the assignment is separated from the variable declaration (which is not the case in the OP's question). Doesn't matter if it is a field or a local variable. Commented May 11, 2018 at 8:55
  • First one is the proper allocation method in java Commented May 12, 2018 at 8:29

1 Answer 1

0

You can have a look at the below method to understand the difference:

public int[] getFewInts() {
   // You can't directly return {1,2,3,4,5};
   return new int [] {1,2,3,4,5};
}

If you wanted to return an int[] array from a method in a single line, you can do that by simply new int [] {1,2,3,4,5}; where as you can't do that with the other one i.e., {1,2,3,4,5}.

The same concept applies when you want to pass the int[] type as a parameter to a method.

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

1 Comment

Same when the declaration and the instantiation are on two statements. int[] array; array = {1,2,3}; The notation can only be used during the declaration.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.