Appearance
How do I declare and initialize an array in Java?
There are several ways to declare and initialize an array in Java. Here are a few examples:
Declare and initialize an array of integers with size 5:
java
int[] array = new int[5];Declare and initialize an array of strings with size 3:
java
String[] array = new String[3];Declare and initialize an array of integers with size 5 and some initial values:
java
int[] array = {1, 2, 3, 4, 5};Declare and initialize an array of strings with size 3 and some initial values:
java
String[] array = {"apple", "banana", "cherry"};Note that in the last two examples, the size of the array is not specified, as it is inferred from the number of initial values provided.
You can also specify the size of the array and the initial values in separate statements:
java
int[] array = new int[5];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;java
String[] array = new String[3];
array[0] = "apple";
array[1] = "banana";
array[2] = "cherry";Keep in mind that in Java, array indexes start at 0, so the first element of the array is at index 0, the second element is at index 1, and so on.