27

Regards to the following code:

int[] to = new int[] { text };

I understand it tries to define an array of integer, but What does the curly braces do in array definition?

2
  • Yes, it looks like you are anonymously subclassing an array, but it is just an initialization Commented Feb 2, 2012 at 14:38
  • I mean if it's seen 5.5k times, it provides a decent quality content I suppose? I googled "curly braces java array" and got this. Better than scouring the ugly Java docs. Commented Sep 12, 2016 at 22:15

5 Answers 5

22

This is just a shortcut code to create an array with initial elements, the followings (which are equal):

    int[] to = new int[] { text };
    int[] to = { text };

can be substituted with

    int[] to = new int[1];
    to[0] = text;

Hope this helps.

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

1 Comment

After 4 years of Java development, I'm only discovering this syntax now. I don't understand why it's not used more. It's so much easier and more sexy than the way that's shown in all the docs - declaration, then manually setting each element in the array.
14

The curly braces contain values to populate the array.

2 Comments

So, currently there is only one element which is 'text', right?
@Leem.fin, Yes, if 'text' is an int - there will be an array 'to' created with one element which is 'text'.
11

This syntax allows you to define the contents of an array and is often referred to as an array literal.

In this context this can actually be simplified to:

int[] to = { 1, 2, 7, etc. };

Adding new int[] before it is only required when not part of an assignment, something like:

someFunction(new int[]{1, 3, 5});

Comments

0

Curly braces said to the compiler the values of the array

1 Comment

So, currently there is only one element which is 'text', right?
0

Like SLaks said, curly braces is a way Java denotes a set. You can define the contents of the array using this method, but each element you define has to be the same type as the array.

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.