Array Initialization
Array initialization is the process of assigning values to the elements of an array. In Java, there are different ways to initialize an array.
Initializing with Curly Braces
The simplest way to initialize an array is by using curly braces {}
. You can list the values inside the curly braces, separated by commas.
Here's an example:
1int[] numbers = {1, 2, 3, 4, 5};
In this example, we have initialized an integer array numbers
with the values 1, 2, 3, 4, and 5.
Initializing with the 'new' Keyword
Another way to initialize an array is by using the 'new' keyword along with the specified size of the array. This method is useful when you want to initialize an array with default values.
Here's an example:
1String[] names = new String[3];
2names[0] = "John";
3names[1] = "Alice";
4names[2] = "Bob";
In this example, we have initialized a String array names
with a size of 3. Then we assign values to each element of the array using the index.
Array initialization is a crucial step in working with arrays. It allows you to prepopulate the array with values so that you can perform operations on them efficiently.
xxxxxxxxxx
// Array Initialization
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];
names[0] = "John";
names[1] = "Alice";
names[2] = "Bob";