2576

How do I declare and initialize an array in Java?

2
  • 45
    Before you post a new answer, consider there are already 25+ answers for this question. Please, make sure that your answer contributes information that is not among existing answers. Commented Feb 3, 2020 at 11:50
  • 2
    docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html Commented Dec 22, 2020 at 9:03

31 Answers 31

1
2
0

It's very easy to declare and initialize an array. For example, you want to save five integer elements which are 1, 2, 3, 4, and 5 in an array. You can do it in the following way:

a)

int[] a = new int[5];

or

b)

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

so the basic pattern is for initialization and declaration by method a) is:

datatype[] arrayname = new datatype[requiredarraysize];

datatype should be in lower case.

So the basic pattern is for initialization and declaration by method a is:

If it's a string array:

String[] a = {"as", "asd", "ssd"};

If it's a character array:

char[] a = {'a', 's', 'w'};

For float double, the format of array will be same as integer.

For example:

double[] a = {1.2, 1.3, 12.3};

but when you declare and initialize the array by "method a" you will have to enter the values manually or by loop or something.

But when you do it by "method b" you will not have to enter the values manually.

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

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.