Declare and initialize array in java

ghz 9months ago ⋅ 167 views

In Java, you can declare and initialize an array using the following syntax:

// Declaration and initialization of an array of integers
int[] numbers = new int[]{1, 2, 3, 4, 5};

// Declaration and initialization of an array of strings
String[] names = new String[]{"John", "Alice", "Bob"};

// Declaration and initialization of an array of doubles
double[] prices = {10.99, 20.49, 5.99, 15.79};

Alternatively, you can declare an array variable first and then initialize it later:

// Declaration of an array variable
int[] numbers;

// Initialization of the array
numbers = new int[]{1, 2, 3, 4, 5};

You can also specify the size of the array without initializing its elements:

// Declaration of an array variable with a specified size
int[] scores = new int[5];

// Initialization of the array elements
scores[0] = 90;
scores[1] = 85;
scores[2] = 95;
scores[3] = 88;
scores[4] = 92;

In this case, the array scores is declared with a size of 5, but its elements are not initialized at the time of declaration. You can later initialize individual elements of the array using the index notation (scores[index]) as shown above.

Note: In Java, arrays have a fixed size once they are initialized, and the size cannot be changed dynamically. If you need a resizable collection, you may consider using ArrayList or other resizable collection classes provided by the Java Collections Framework.