Array Creation and Access
Learn how to create an array and access data from it, in Java.
We'll cover the following...
Let’s build an easy scenario before moving any further. Suppose a teacher has to grade papers in total. As a programmer, you don’t want to make five different variables for it. Let’s get this done with arrays.
Create an array
Look at the code below.
class CreateArray{public static void main(String args[]){int[] marks = {100, 87, 93, 76, 45}; // Creating an array}}
We take marks as integers. Look at line 5. Let’s go through it:
int
: Type of the values you want in an array[]
: Square brackets right after the typemarks
: Name of the array variable
Up until now, the array marks
have been declared. In the other part, we add the values. Values are added within {}
(curly braces). Note: we add five values, as discussed above, when building the scenario.
⚙️ Note: Arrays can store either primitive data (like
int
) or object reference data (likeStrings
or a custom class).
The new
keyword
What if, we don’t want to add values at the time of creation? For this, Java has a keyword: new
. Let’s modify the program above.
class CreateArray{public static void main(String args[]){int[] marks = new int[5]; // Creating array with 'new' keyword}}
The size of an array is established at the time of creation and cannot be changed.
Access elements of an array
Square brackets ([ ]
) are used to access and modify an element in an array using an index. Look at the program below.
class AcessArray{public static void main(String args[]){int[] marks = {100, 87, 93, 76, 45}; // Creating an arraySystem.out.println(marks[0]); // Acessing an element}}
Initially, we make an array of five elements. Look at line 6. We print marks[0]
.
It prints the value at th index (first value): ...