Arrays in Java | Part 2

What happens when we create array?

When we create an array, memory is allocated for each data. And all data are given index number so that we can find exact data we are looking for.

Lets go deeper: for example I created an array with 10 numbers.

int[] nums = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
In figure:

Note that index always starts at 0, That means last index will always be one less than total size.

In above example, we can see that each data have its own index number, So to access data, we can write variable with its index number in square breackets. In this case, it is nums[0] = 10, nums[1] = 20, nums[2] = 30, ..... , nums[9] = 100.

Insert and Access data in an array

Since we have array and index, we can insert or access data easily. To access data, we can do this:

and to insert data we can do this:
Array[index] = value;


Lets see an example of declaring, creating, inserting and accessing data in array.

public class LearnArray { public static void main(String[] args) { //creating arrays int[] age = new int[3]; String[] name = new String[3]; //inserting data in arrays age[0] = 18; name[0] = "Johny"; age[1] = 20; name[1] = "Depp"; age[2] = 22; name[2] = "Javier"; //accessing data in arrays System.out.println("Age: "+age[0]+" Name: "+name[0]); System.out.println("Age: "+age[1]+" Name: "+name[1]); System.out.println("Age: "+age[2]+" Name: "+name[2]); } }
Age: 18 Name: Johny
Age: 20 Name: Depp
Age: 22 Name: Javier

This example is for breiefing only. We access array data with loops which we will discuss in next topic.

Arrays in Java Previous Next For and For Each Loop in Java Array