How do I declare and initialize an array in Java?
-
45Before 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.janniks– janniks2020-02-03 11:50:43 +00:00Commented Feb 3, 2020 at 11:50
-
2docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.htmlBabak– Babak2020-12-22 09:03:30 +00:00Commented Dec 22, 2020 at 9:03
31 Answers
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.