![]() |
VOOZH | about |
An array is a collection of elements of the same data type stored in contiguous memory locations. It allows multiple values to be stored under a single name and accessed using an index.
Primitive Array -> 10 20 30 40 Non-Primitive Array -> Lakshit Rahul Pankaj
Explanation:
String objects and is printed in the same way using its length property.In Java, an array is declared by specifying the data type, followed by the array name, and empty square brackets [].
Syntax:
dataType[] arrayName;
or
dataType arrayName[];
When an array is declared, only a reference is created. Memory is allocated using the new keyword by specifying the array size.
Syntax:
int arr[] = new int[size];
You can use array literals to initialize an array when declaring it. In this case, the new keyword is not required-
Example:
int[] arr = {1, 2, 3};
Elements of an array can be accessed by their position, called the index. In Java, array indexing starts from 0 (not 1). To access an element, provide the index inside square brackets [] along with the array name.
12 2
Note: It is important to note that index cannot be negative or greater than size of the array minus 1. (0 ≤ index ≤ size - 1). Also, it can also be any expression that results in valid index value.
To update an element at a specific index in an array, use the assignment operator = while accessing the array element and assign a new value.
90
Traversing an array means accessing each element one by one. In Java, arrays can be easily traversed using a loop where the loop variable runs from 0 to array.length - 1.
2 4 8 12 16
The size of an array refers to the number of elements it can hold. To find the size of array java provides a built-in property called length.
Size of array: 5
An array of objects is created like an array of primitive-type data items
Example: Create an array of five Student objects by instantiating each Student using its constructor and storing their references in the array.
Element at 0 : { 1 aman }
Element at 1 : { 2 vaibhav }
Element at 2 : { 3 shikar }
Element at 3 : { 4 dharmesh }
Element at 4 : { 5 mohit }
JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of an array.
Output:
Like variables, we can also pass arrays to methods. For example, the below program passes the array to method sum to calculate the sum of the array's values.
sum of array values : 15
As usual, a method can also return an array. For example, the below program returns an array from method m1.
1 2 3