Java Arrays

Section 1

Introduction to Arrays

In this lesson, we will begin looking at what an Array is, and how to create or declare an Array in Java.

Opening Problem

  1. Suppose you want to find the average of the grades for a class of 30 students. You certainly do not want to create 30 variables, such as mark1, mark2, ..., mark30.

    • Solution: Use a single variable, called an Array, with 30 elements (or items).

Topic 1a: Overview of Array

  • An Array is a data structure, which stores a fixed-size sequential collection of elements of the same type. A Java Array length cannot be changed.

  • An Array is used to store a collection of data or a collection of similar types of elements, which have contiguous memory location.

  • An Array in Java is an object because the direct Superclass of an Array is Object Class. Since Arrays are objects, all methods of Object Class may be invoked on an Array.

  • All Arrays are reference types no matter their element type. Memory for Arrays is always allocated on the heap memory.

  • In Java, an Array can hold both primitives values and objects type values.

  • In array, Elements start with an index of zero and end with an ending index of length -1.

Topic 1b: Declare and Initialize Arrays in Java

Declare and Initialize Arrays in Java by:

  • Declaration without initializing elements/values.

  • Declaration using a new operator.

  • Declaration and initialization in one step.

Declaration Without Initializing Elements/Value

  1. Syntax → datatype[] arrayName; Example:

    • double[] arrayName;

    • String[] arrayName;

    • int[] arrayName;

  2. Syntax → datatype arrayName[]; Example:

    • double myList[];

Declaration Using a New Operator

  • Syntax → datatype[] arrayName = new datatype[arraySize];

  • Example:

    • double[] myList = new double[10]; //allocates memory for myList. myList[0] //references the first element in the array.

    • myList[9] //references the last element in the array.

    • Instead of hard-coding for the last element, we could use the array’s length. It is useful when the last index is unknown:

    • myList[myList.length - 1] //references the last element in the array.

Example: Declaration Using a New Operator

public static void main(String args[]) {
    int month_days[];
    month_days = new int[12];
    month_days[1] = 28; // declaring and creating array with size
    month_days[0] = 31; // initializing values
    month_days[2] = 31; // initializing values
    month_days[3] = 30; // initializing values
    month_days[4] = 31; // initializing values
    month_days[5] = 30; // initializing values
    month_days[9] = 31; // initializing values
    month_days[6] = 31; // initializing values
    month_days[8] = 30; // initializing values
    month_days[10] = 30; // initializing values
    month_days[11] = 31; // initializing values
    System.out.println("April has " + month_days[3] + " days."); // In Arrays, we can access the specific element by its index within square brackets.
}

Output: April has 30 days.

Array Declaration and Initialization in One Step

We can also declare and initialize Arrays in a single line without using a new operator, as shown below:

Syntax → dataType[] arrayName = { comma separated values };

Example → double[] myList = {1.9, 2.9, 3.4, 3.5};

The above statement is equivalent to the following statements:

double[] myList = new double[4];

myList[0] = 1.9;

myList[1] = 2.9;

myList[2] = 3.4;

myList[3] = 3.5;

Remember: Array declaration and initialization must be done in a single statement. For example, the following statement is incorrect and will not compile:

double[] myArray;
myArray = {1.9, 2.9, 3.4, 3.5};

Example: Array Declaration and Initialization in One Step

The following code creates an initialized Array of integers:

public static void main(String args[]) {
    int[] month_days = {31,28,31,30,31,30,31,30,31,30,31};
    System.out.println("April has " + month_days[3] + "days.");
}

In Arrays, we can access the specific element by its index within square brackets.

Output:

April has 30 days.

Array Declaration and Initialization in One Step

We can also declare and initialize Arrays in a single line without using a new operator, as shown below:

Syntax → dataType[] arrayName = { comma separated values };

Example → double[] myList = {1.9, 2.9, 3.4, 3.5};

The above statement is equivalent to the following statements:

double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

Remember: Array declaration and initialization must be done in a single statement. For example, the following statement is incorrect and will not compile:

double[] myArray;
myArray = {1.9, 2.9, 3.4, 3.5};

Example: Array Declaration and Initialization in One Step

The following code creates an initialized Array of integers:

public static void main(String args[]) {
    int[] month_days = {31,28,31,30,31,30,31,30,31,30,31};
    System.out.println("April has " + month_days[3] + "days.");
}

In Arrays, we can access the specific element by its index within square brackets.

Output:

April has 30 days.

Topic 1c: Access Elements of an Array in Java

Array Indexing:

  • The array elements are accessed by index. Array indexing is 0-based (e.g., ranging from 0 to arrayVar.length-1):

double[] myList = new double[10];
//myList holds 10 elements indexed from 0 to myList.length-1
  • Each element in the array can be accessed using the following syntax, known as an indexing expression, or simply indexer.

arrayVar[index];  // index is an integer

Using Indexed Variables:

  • After an array is created, its indexed variables can be used in the same way as regular variables. The following statement adds the first two values in an array and assigns the result to the third index in the array:

myList[2] = myList[0] + myList[1];
  • Be careful not to attempt to access values past the end of the array:

double val = myList[10];// Causes an exception!! This results in an ArrayIndexOutOfBoundsException.

Topic 1d: The Length of an Array

  • Once an Array is created, its size is fixed, and cannot be changed.

  • An array’s size is given by its length property:

int size = arrayRefVar.length;
  • For example: myList.length; // returns 10

Example - The Length of an Array

public class Test {
    public static void main(String[] args){
        // Here str is the array name of String type.
        String[] str = { "Java", "FOR", "EVERYONE" };
        System.out.println(str.length);
    }
}

Explanation:

  • Here, the str is an array of type string, and that is why str.length is used to find its length.

  • Output: 3

Section 2

Iterating Over an Array Using Loop

In this lesson, we will discuss Traverse through an array.

Topic 2a: Traverse Through Array Using for Loop

Array Access With a for Loop - 1:

  • In Java, we can also loop through each element of the array.

public class Test {
    public static void main(String[] args) {
        // Here, the array is initialized with values
        double[] myList = {1.9, 2.9, 3.4, 3.5};
        // printing all the array elements
        for (int i = 0; i < myList.length; i++) {
            System.out.println(myList[i]);
        }
    }
}

Array Access With a for Loop - 3

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

i (=1) is less than 5, so the looping begins. 21

Array Access With a for Loop - 4

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

After this line executes, values[1] has been assigned 1. 22

Array Access With a for Loop - 5

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

After i++, i has a value of 2. 23

Array Access With a for Loop - 6

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

i (= 2) is less than 5, so the looping continues. 24

Array Access With a for Loop - 7

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

After this line executes, values[2] has been assigned 3. 25

Array Access With a for Loop - 8

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

After i++, i has a value of 3. 26

Array Access With a for Loop - 9

public class Test {
public static void main(String[] args) {java
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

i (=3) is still less than 5, so the looping continues. 27

Array Access with a for Loop - 10

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (

Array Access With a for Loop - 13

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

After this line executes, values[4] has been assigned 10.

Array Access With a for Loop - 14

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

After i++, i has a value of 5.

Array Access With a for Loop - 15

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

i < 5 evaluates false. The loop exits.

Array Access With a for Loop - 16

public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
  values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}

After this line executes, values[0] has been assigned 11.

Topic 2b: Array Access With an Enhance - for Loop

JDK 5 introduces a new loop syntax known as enhanced for-loop (or for-each loop) to facilitate processing of arrays and collections. It takes the following syntax:

for (dataType item : array) {
  ...
}

Example: Print Array Elements

public static void main(String[] args) {
  // create an array
  int[] numbers = {3, 9, 5, -5};
  // for each loop
  for (int number: numbers) {
    System.out.println(number);
  }
}

Here:

  • Item - each item of array is assigned to this variable.

  • DataType - the datatype of the Array.

  • Array - an Array.

Hands-On Lab

Complete this lab GLAB - 303.6.1 -Array. You can find this lab on Canvas under the Assignment section. If you have technical questions while performing the lab activity, ask your instructors for assistance.

Section 3

Overview of Multidimensional Arrays

In Java, we can declare an array of arrays, known as a multidimensional array or two-dimensional array. In a two-dimensional array, the elements can be arranged in rows and columns. Syntax:

datatype[][] arrayName = new datatype[row][column];

Illustration of a 6 x 5 array (6 rows, 5 columns):

1 - Declaring a Multidimensional Array

Consider the following matrix, which has integer elements and consists of six rows and five columns.

Last updated