Leem.fin
Leem.fin

Reputation: 42642

curly braces when define array

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?

Upvotes: 26

Views: 36772

Answers (5)

danyim
danyim

Reputation: 1293

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.

Upvotes: 0

Egor
Egor

Reputation: 40218

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.

Upvotes: 22

James Montagne
James Montagne

Reputation: 78690

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});

Upvotes: 11

user1151835
user1151835

Reputation:

Curly braces said to the compiler the values of the array

Upvotes: 0

SLaks
SLaks

Reputation: 887857

The curly braces contain values to populate the array.

Upvotes: 14

Related Questions