Skip to content

Array

In programming, we need a mechanism to store and manipulate a group of similar data.  Java offers a code construct called Array to work with a collection of data as one entity.

In this module, we will cover the following topics to understand an array:

  • Intro to Array
  • Creating an Array
  • Array Indexing
  • Array Size



› Intro to Array

An array is a collection that holds multiple data values of the same data type.  Each data value of the array is called an element.

Array creation syntax:

dataType[]  variable  = new dataType[ numberOfElements ];

Array creation example:

Example 1
1
2
3
4
5
int[] ages = new int[4];

// You can also do
int[] ages;
ages = new int[4];

Let's see what is going on with the above Example 1 code:

code segment explanations
int[] integer array data type specification, The symbol [] specify an array
ages array variable name, name should bea plural
= assignment operator
new keyword that creates new memory space in RAM
int[4]; specifies how many elements should be in the array

We can also visualize the above array as follows:

explanation

This integer array is accessible via the ages variable. This array can store four integer data values.   This array is currently holds four default integer data values ( 0 ).   In order to access or update each of these integer data value, we use the index or position number.



› Creating an Array

Arrays can be created using literal syntax or constructor syntax.   Both are excellent ways to create an array depending on your needs.

Let's take a look at creating the following ages array on both ways:

int[] ages = {12, 4, 5, 2};

Create an array this way when you know:

  • how many elements will be stored in the array.
  • data values for each array element.
1
2
3
4
5
int[] ages = new int[4];
ages[0] = 12;
ages[1] = 4;
ages[2] = 5;
ages[3] = 2;

This way of creating an array has the advantage of creating an array with a specific capacity. For example, we could easily create this ages array with 100 elements capacity like this:

int[] ages = new int[100];
This is especially helpful when we don't know how many elements we want to group in the array, but we can create large enough to accommodate if we had to group a larger number of age numbers.

Let's see another example of creating same array in two different ways:

literal syntax
1
2
3
4
5
6
int[] creditScores = { 560, 683, 710, 810 };
String[] trainingDays = {"Sun", "Mon", "Tue","Wed"};

// Outputs:
System.out.println( Arrays.toString(creditScores) );
System.out.println( Arrays.toString(trainingDays) );

constructor syntax
// 2:  Conventional Array creation way
int[] creditScores = new int[4];
creditScores[0] = 560;
creditScores[1] = 683;
creditScores[2] = 710;
creditScores[3] = 810;

String[] trainingDays = new String[4];
trainingDays[0] = "Sun";
trainingDays[1] = "Mon";
trainingDays[2] = "Tue";
trainingDays[3] = "Wed";

// Outputs:
System.out.println( Arrays.toString(creditScores) );
System.out.println( Arrays.toString(trainingDays) );
J-editor ♞



› Array Indexing

An array classifies as an indexed data collection in computer science.  This means that each data value in the array can be accessed via index or position number that usually starts with zero.  Using this index number to work with one of the data value in the array is generally called indexing.

Indexing syntax:

arrayVariable[ index-number ]; 

With indexing, array slot position number starts with the number 0 instead of 1. If the number of elements in ages array is 4, the first element of the array can be accessed via indexing ages[0], and the last element will be ages[3].

Consider indexing example with previous ages array:

1
2
3
4
5
int[] ages = new int[4];

// indexing: access array elements
int a = age[1]; // refers to the second data value in the array
int b = age[3]; // refers to the fourth data value in the array

Image title

The integer variable a and b will hold the second and fourth element of the ages array. The indexing here for each of these code are as follows:

  • ages[1]:  2nd slot of an array
  • ages[3]:  4th slot of an array

It is important to note that if you use a negative integer number for index or a number that is greater than a possible index number, it will result in an exception ( error for programmers ) known as ArrayIndexOutOfBoundsException.

1
2
3
4
// illegal indexing: 
// It will throw ArrayIndexOutOfBoundsException 
int a = age[-1];  // results in exception 
int b = age[5];   // results in exception, we don't have sixth data in the array

Try this indexing sample code in code editor:

// create an array of length 5  
int[] age = new int[4];

// access each element of the array using the index number 
System.out.println( age[0] ); 
System.out.println( age[1] );
System.out.println( age[2] );  
System.out.println( age[3] );

System.out.println( age[4] ); // <-- ERROR!
J-editor ♞

As you can see, If you do not specify a particular value to each slot of the array, the default value of the data type will be stored instead.   For the data types we know so far, their default values are as follows:

Date Type Default Data Value
int 0
double 0.0
char empty character symbol
boolean false
String null

Try the following sample code to see that empty arrays contains data type default values for each of its slots.

Empty array contains default values
// Create an empty array for each data types
int[] callHistories = new int[6];
double[] balances = new double[6];
char[] grades = new char[6];
boolean[] completions = new boolean[6];
String[] friends = new String[6];

// Output the contents of each empty arrays
System.out.println(  Arrays.toString(callHistories) );
System.out.println(  Arrays.toString(balances)      );
System.out.println(  Arrays.toString(grades)        );
System.out.println(  Arrays.toString(completions)   );
System.out.println(  Arrays.toString(friends)       );

// Output should contain default data value for each type
//  [0, 0, 0, 0, 0, 0]
//  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
//  [ ,  ,  ,  ,  ,  ]
//  [false, false, false, false, false, false]
//  [null, null, null, null, null, null]
J-editor ♞

Assigning data value to array slot:

Assigning or updating the data value for an array slot is also achieved using indexing.

The syntax:

arrayName[index] = data_value;

for example if we have an array of integers called age, and if you want to assign 18 as its first element:

1
2
3
// Example 
int[] age = new int[5];
age[0] = 18;   // assigning integer data value 18 to the first slot of age array, 

Note that assigning incompatible data value to the array, it will result in programming error:

age[1] = "Nijat";  // trying to assign a String data value

Now, try out this code that creates an integer array, assigns a data value in each of its slots, and display them to the screen one by one.

// create an array of length 5  
int[] age = new int[5];

// assign a data value to each of array slot
age[0] = 18;
age[1] = 22;
age[2] = 36;
age[3] = 45;
age[4] = 28;

// access each element of the array using the index number
// display them to the terminal window 
System.out.println(age[0]);     // prints: 18 
System.out.println(age[1]);     // prints: 22 
System.out.println(age[2]);     // prints: 36 
System.out.println(age[3]);     // prints: 45 
System.out.println(age[4]);     // prints: 28 
J-editor ♞



› Array Size

Once you declared an array by specifying the number of elements like below:

1
2
3
4
5
6
7
8
9
// specified that array should hold 5 elemetns 
int[] myArray = new int[5];  

// giving data value for each elements
myArray[0] = 2; 
myArray[1] = 4; 
myArray[2] = 6; 
myArray[3] = 8; 
myArray[4] = 10;

its size is always fixed, for example, myArray size is always fixed to 5. You CANNOT change the array size. If you need to extend the array size, you need to create a new bigger array with the desired size and copy over the array element values and delete the small array. That is the only way we can increase the array size. However, please note that it is very rated to change the array size in Java programming.

Getting Array Size:

Using .length property of an array will return the size of an array, meaning how many elements are inside of this array.

myArray.length;   // this will return integer value 5

Also, we can use the .length property of an array to calculate it's last index number.

myArray.length - 1

Let's see an code example:

Last Index
// Given the following array:
// Index         0       1     2    3     4
double[] gpa = {3.32, 2.27, 3.33, 3.65, 3.87};

// Printing the last element value by typing the last index
System.out.println("Last Element: " + gpa[4]);

// Printing the last element value using .length calculation
int lastIdx = gpa.length - 1;
System.out.println("Last Element: " + gpa[lastIdx]);

// Or Just simply
System.out.println("Last Element: " + gpa[gpa.length - 1]);
J-editor ♞