
Java Arrays
An array is a structured collection of data elements that share the same type, enabling you to group multiple values under one variable name and access them via an index. For instance, if you want to store the ages of 50 individuals, you can declare an int
array to hold these 50 age values.
To declare an array, you need to specify the data type, followed by square brackets []
, and then give your array a name:
You can then create the array using the new
keyword and specify the number of elements it will contain:
Alternatively, you can combine declaration and initialization in a single line:
It’s important to note that the size of an array is fixed once it is created. To change the size, you’ll need to create a new array. Additionally, elements in newly created arrays are automatically initialized to default values (e.g., 0
for integers and false
for booleans).
You can assign values to individual elements of an array either separately or at the time of declaration:
Array elements can be accessed using zero-based indexing, where the first element is located at index 0
, the second at index 1
, and so forth.
To find out how many elements are in an array, you can use the length
property of the array.
Here’s a complete example:
Output