1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 4. Data Structures


Lesson Objective

  • Understand the concept of arrays and how they are applied in Java.
  • Be able to interpret and use 1 and multidimensional arrays in Java.

Lesson Notes

Java Arrays - Initiate

To create an array, first declare a variable and then allocate memory for it using the new keyword. For instance, if you want to declare an array of integers, do the following.

Code:

public class Hello_World_1 {
   public static void main(String args[]){ 
      int[] numbers = new int[5];
   }
}
// This will create an array of 10 integers, and each element of the array will be initialized to the default value for its type, which is 0 in this case.

Cmd Output:


Arrays are used to store multiple values within a single variable, eliminating the need for separate declarations for each value.

To create an array, specify the variable type using square brackets. You can also initialize an array using an array literal, which consists of a list of values enclosed in curly braces.

Code:

public class Hello_World_1 {
   public static void main(String args[]){ 
      String[] fruits = {"apple", "pear", "mango"};
   }
}
// fruits variable holds an array of strings. The values are inserted inside curly braces. This also sets the size of the array.
// To create an array of integers, you could write:
// int[] myNum = {10, 20, 30, 40};

Cmd Output:



Java Arrays - Access

To display an array's contents, you import the Arrays.toString() method. Additionally, you can use the wildcard character * to import all classes from the Java package framework.

Code:

import java.util.*;
public class Hello_World_1 {
   public static void main(String args[]){ 
      String[] fruits = {"apple", "pear", "mango"};
      System.out.println(Arrays.toString(fruits));
   }
}

Cmd Output:

[“apple”, “pear”, “mango”]

Indexing

To access a single item in an array, you refer to its index position. Each item is assigned a number, and the first item is denoted as position “0”.

To display specific elements of an array, reference the array variable and specify the index position of the desired element. Keep in mind that index position 0 corresponds to the first item.

Code:

import java.util.*;
public class Hello_World_1 {
   public static void main(String args[]){ 
      String[] fruits = {"apple", "pear", "mango"};
      System.out.println(Arrays.toString(fruits));
      System.out.println(fruits[0]);
   }
}

Cmd Output:

[“apple”, “pear”, “mango”]
apple

Java Arrays - Edit

To modify the value of a specific element, simply access it using its index number and assign a new value.

Code:

public class Hello_World_1 {
   public static void main(String args[]){
      String[] fruits = {"apple", "pear", "mango"};
      System.out.println("fruit 2 =");
      System.out.println(fruits[1]);
      fruits[1] = "tomato";
      System.out.println("fruit array updated...");
      System.out.println("fruit 2 =");
      System.out.println(fruits[1]);

   }
}

Cmd Output:

fruit 2 =
pear
fruit array updated...
fruit 2 =
tomato

Java Arrays - Length

To find out how many elements an array has, use the length property.

Code:

public class Hello_World_1 {
   public static void main(String args[]){
      String[] fruits = {"apple", "pear", "mango"};
      System.out.println("fruit 2 =");
      System.out.println(fruits[1]);
      fruits[1] = "tomato";
      System.out.println("fruit array updated...");
      System.out.println("fruit 2 =");
      System.out.println(fruits[1]);
      System.out.println(fruits.length);
   }
}

Cmd Output:

fruit 2 =
pear
fruit array updated...
fruit 2 =
tomato
3

Java Arrays - Adding Elements

An array is a sequential data structure used to store a collection of elements with similar data types. Once created, an array's size cannot be changed; it remains of fixed length. Adding an element to a given array however is a vastly common operation. Here are some links that can help.

https://www.tutorialspoint.com/how-to-add-an-element-to-an-array-in-java


Java Arrays - For Loops

You can iterate through array elements using a for loop, and the length property determines how many times the loop should execute.

Code:

public class Hello_World_1 {
   public static void main(String args[]){
      String[] fruits = {"apple", "pear", "mango"};
      System.out.println("fruit 2 =");
      System.out.println(fruits[1]);
      fruits[1] = "tomato";
      System.out.println("fruit array updated...");
      System.out.println("fruit 2 =");
      System.out.println(fruits[1]);
      System.out.println(fruits.length);

      for (int i = 0; i < fruits.length; i++) {
         System.out.println(fruits[i]);
      }
   }
}

Cmd Output:

fruit 2 =
pear
fruit array updated...
fruit 2 =
tomato

apple
tomato
mango

System.out.print can be used instead of System.out.println to display all the elements on a single line.

Code:

public class Hello_World_1 {
   public static void main(String args[]){
      String[] fruits = {"apple", "pear", "mango"};
      System.out.println("fruit 2 =");
      System.out.println(fruits[1]);
      fruits[1] = "tomato";
      System.out.println("fruit array updated...");
      System.out.println("fruit 2 =");
      System.out.println(fruits[1]);
      System.out.println(fruits.length);

      for (int i = 0; i < fruits.length; i++) {
         System.out.print(fruits[i]);
      }
   }
}

Cmd Output:

fruit 2 =
pear
fruit array updated...
fruit 2 =
tomato

appletomatomango

Java Arrays - For Each Loops

A “for-each” loop is specifically designed for iterating through elements in arrays.

Code:

public class Hello_World_1 {
   public static void main(String args[]){
      String[] fruits = {"apple", "pear", "mango"};
      for (String i : fruits) {
         System.out.println(i);
      }
   }
}
// The example above can be read like this: for each String element (called i - as in index) in fruits, print out the value of i.
// If you compare the for loop and for-each loop, you will see that the for-each method is easier to write, it does not require a counter (using the length property), and it is more readable.

Cmd Output:

apple
tomato
mango

Java Arrays - Multidimensional Array

A multidimensional array is essentially an array of arrays.

These arrays are particularly useful when you need to store data in a tabular format, similar to a table with rows and columns.

Code:

public class Hello_World_1 {
   public static void main(String args[]){
      int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
      System.out.println(myNumbers[1][2]);

   }
}
// To create a two-dimensional array, add each array within its own set of curly braces.
// The array variable followed by the subarray position and then the position of the data would be used to select data items.

Cmd Output:

7

To modify the value of a specific element, simply access it using its index number and assign a new value.

Code:

public class Hello_World_1 {
   public static void main(String args[]){
      int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
      myNumbers[1][2] = 9;
      System.out.println(myNumbers[1][2]); 
      // Outputs 9 instead of 7
   }
}
// Same process as a 1 dimensional array

Cmd Output:

9

When working with a two-dimensional array, you can nest a for loop inside another for loop to access its elements. Remember that you’ll need to refer to two indexes to pinpoint the specific element you want to manipulate.

Code:

public class Hello_World_1 {
   public static void main(String args[]){
      int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
      System.out.println(myNumbers[1][2]);
      myNumbers[1][2] = 8;

      for (int i = 0; i < myNumbers.length; ++i){
         for (int j = 0; j < myNumbers[i].length; ++j){
            System.out.println(myNumbers[i][j]);
         }
      }
   }
}

Cmd Output:

1
2
3
4
5
6
8

3