- Arrays are versatile and commonly used in Java for storing and manipulating collections of data.
- In Java, an array is a simple, data structure that stores a static/fixed-size sequential collection of elements of the same data type(homogenous elements).
- Arrays in Java have a fixed size, meaning once they are created, their length cannot be changed. To create a dynamic collection/array in Java that can grow or shrink in size, we can use other data structures such as ArrayList from the Java Collections framework.
- Arrays have a fixed size once they are created, and this size cannot be changed during runtime.
- Arrays are used to store multiple values of the same data type under a single variable name, making it convenient to manage and access elements using indexes.
- Arrays provide a convenient way to work with collections of elements, such as a list of numbers or a group of objects.
- To declare an array of integers, we use as –
int[] arrayname; or int arrayname[];
Now to create an array with 5 elements
arrayname= new int[5];
- To assign static values to the array elements
- We can also initialize an array with constant values at the time of declaration:
int[ ] arrayname= {100, 200, 300, 400, 500};
- The individual elements of the array can be accessed using square brackets
[]
and an index number/location. - Array indices start from 0, so arrayname[0] refers to the first element, arrayname[1] refers to the second element, and so on.
- The length of an array can be obtained using the
length
property. - We can use a loop to iterate over or display the elements of an array:
The arrayname.length
returns the length or size of the array, allowing it to iterate over all the elements using a loop.
- Java also supports multi-dimensional arrays:-
int[ ][ ] arr= new int[3][3]; // 3×3 size two-dimensional array (3 rows, 3 columns).
0 Comments