Array
Array is a set of elements. Instead of using multiple variables for multiple data, we can store SIMILAR types of data in an array
.
datatype[] array = {element1, element2, ....};
Same as declaring a variable for a single data, we need to declare the data type of the elements inside an array
. After declaring the data type, we need to add square brackets []
to let the compile know that we are assigning an array
to a variable. After that we need to give the variable a name, same as before and lastly to store elements in an array, java use curly braces {}
and inside the braces we can put the values separating by ,
. For example,
int[] numbers = {10, 20, 30};
Now let us see what will happen if we try to print this array in the console.
public class Array {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println(numbers);
}
}
Output
[I@2a84aee7
The output will be something like this. But this is not what we wanted to print.
When we create an array, it stores the location (ram location) of values instead of the actual values. However, we can fetch the actual values using the location and indexing.
Indexing
Every element inside an array has an unique index value. Index starts from 0 to n-1 where n
is the number of elements inside an array. So, the first element of an array has index of 0 and second element has 1 and so on.
int[] numbers = {10, 20, 30};
Indexing of this array
Index | 0 | 1 | 2 |
---|---|---|---|
Elements | 10 | 20 | 30 |
To fetch the values we can write the following code,
public class Array {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);
}
}
So first we need to write the variable where the array location has been stored in this case the variable name is numbers
, then inside square brackets []
we will pass the index of the values. If the index number exceeds the array, it will give an error.
Output
10
20
30
We can use Loops as well to iterate through the whole array.
Appendix
- Arrays can be formed of any data types but the data type of all the elements inside an array must be the same. For example,
String[] names = {"Alvin", "Simon", "Theodore"};
double[] gpa = {3.70, 3.30};
- Elements inside an array can be changed by using index.
gpa[1] = 4.00;
- We can create an array of a certain size before assigning the values inside it. Then we can add elements using indexes.
int[] numbers = new int[10];
numbers[0] = 50;
- We cannot add elements exceeding the length of the array.
Happy Coding
Top comments (0)