0

I know there are two ways to create an array with given initial value

  1. int[] ary1 = new int[]{1,2,3,4};

  2. int[] ary1 = {1,2,3,4};

What exactly is the difference between those?

3 Answers 3

2

There is no difference in your example.

However, there is one extra feature that new type[] provides - array length:

Like so:

String[] names = new String[5];

Which makes a new String array with the capacity to hold 5 items. If one of the items is not populated, it will return null.

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

1 Comment

The new String[5]; does not have 5 items in it. It has the capacity to hold 5 items but the way it is written each spot is actually null. #1 in how you would populate the array after you call new in a single command.
1

Both of your statements will create and initialize an array. However, the following example illustrates a difference:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        print(new int[] { 1, 2, 3, 4 });
        // print({ 1, 2, 3, 4 });// Won't be compiled
    }

    static void print(int[] arr) {
        System.out.println(Arrays.toString(arr));
    }
}

2 Comments

if edit it to this way, it can work, why? int[] ar1 = new int[] { 1, 2, 3, 4 }; int[] ar2 = { 1, 2, 3, 4 }; print(ar1); print(ar2);
@theabc50111 - Whatever you have written in the comment is as per the Java syntax. I am glad to see that you have a great curiosity and appetite to learn the concept clearly.
0

Both of the following are equivalent.

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

But the {} method can only be used when the array is declared. So

int[] ary1;
ary1 = {1,2,3,4}; // not permitted.

Nor is

for (int a : {1,2,3,4}) {
  // do something
}

It has to be

for (int a : new int[] {1,2,3,4}) {
  // do something
}

Comments

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.