[Java] [Introduction to Java] About array operations (declaration, instantiation, initialization and use of one-dimensional and two-dimensional arrays)

12 minute read

Purpose

Those who have just started learning programming including Java language, those who have already learned, for reviewing, This time I am writing to learn about arrays.

[Introduction to Java]Variables and typesType conversionVariable scopeCharacter string operation ・Operation of array ← now here ・Operator ・Conditional branch (in preparation) ・Repeat processing (in preparation) ・About class (in preparation) ・Abstract class (in preparation) ・Interface (in preparation) ・Encapsulation (in preparation) ・About module (in preparation) ・About exception handlingAbout LambdaAbout Stream API

What is an array

A variable is a container that contains one value data for one variable (Click here for variables),

By using array, multiple data of the same data type can be managed by one array.

When there are values for 500, you have to prepare 500 for variables. In the case of array, it means that one array can be prepared and 500 pieces of data can be stored in it.

Also, you can easily sort the data in the array and get the largest value.

1 dimensional array declaration

When creating an array, it is necessary to first decide the data type of what kind of value is to be treated and to declare it with a name, as with variables.

Declare data type[] array name.

Main.java


class Main {
  public static void main(String[] args) {
    int[] numbers; // array declaration that can handle int type values

    // [] can be after the array name.
    String names[]; // Array declaration that can handle String type values
  }
}

Instantiate a 1-dimensional array

You have to secure an area to fill the declared array with values. Determine the size of the area to secure with new [number of elements].

Main.java


class Main {
  public static void main(String[] args) {
    int[] numbers; // array declaration that can handle int type values
    String names[]; // Array declaration that can handle String type values

    numbers = new int[50]; // Reserve an area for storing 50 values in the numbers array
    names = new String[3]; // Allocate space for storing 3 values in name array
  }
}

** It is also possible to declare the array and secure the area at the same time. **

Main.java


class Main {
  public static void main(String[] args) {
    int[] numbers = new int[50]; // Declare an array that can handle int type values and secure 50 areas
    String names[] = new String[3]; // Declaration of array that can handle String type value and secure area for 3
  }
}

**Note that if you do not specify the number of elements, a compile error will occur. **

Main.java


class Main {
  public static void main(String[] args) {
    int[] numbers = new int[]; //Compile error because the number of elements is not specified
    String names[] = new String[]; //Compile error because the number of elements is not specified
  }
}

The number of elements in the array cannot be changed later, Keep in mind that if you first specify the number of elements in the array as 5, the number of elements after that will be fixed at 5.

Also, keep in mind that the number of elements must be an integer.

1 dimensional array subscript (index) and value storage

You are ready to store values by declaring and instantiating the array. To assign a value to an array, use the subscript (index). The subscript (index) is a serial number given to each element of the array and starts from 0.

Main.java


class Main {
  public static void main(String[] args) {
    int[] numbers = new int[5]; // define numbers array that can store 5 elements of int type
    numbers[0] = 100; // 100 for the first
    numbers[1] = 200; // 200 for the second
    numbers[2] = 300; // the third is 300
    numbers[3] = 400; // 400 for the fourth
    numbers[4] = 500; // fifth, 500
  }
}

A subscript (index) is also used when accessing each element of the array.

Main.java


class Main {
  public static void main(String[] args) {
    int[] numbers = new int[5]; // define numbers array that can store 5 elements of int type
    numbers[0] = 100; // 100 for the first
    numbers[1] = 200; // 200 for the second
    numbers[2] = 300; // the third is 300
    numbers[3] = 400; // 400 for the fourth
    numbers[4] = 500; // fifth, 500

    System.out.println(numbers[0]); // prints 100
    System.out.println(numbers[3]); // prints 400
  }
}

One-dimensional array initialization

Up to the above, array declaration, allocation of area, and assignment of value (initial value) were done in order,

You can declare an array, secure an area, and assign a value (initial value) all at the same time. (Initialization of array)

Enclose the value in {} and describe each element with a comma. Data type [] array name = {initial value 1, initial value 2, initial value 3, initial value 4, initial value 5};

Also, use length to check the number of created elements. You can get the number of elements with array name.length;.

Main.java


class Main {
  public static void main(String[] args) {
    int[] numbers = {100, 200, 300, 400, 500}; // array initialization
    int size = numbers.length; // Get the number of elements in the numbers array In this case, 5 is stored

    System.out.println(numbers[0]); // printed as 100
    System.out.println(numbers[1]); // printed as 200
    System.out.println(numbers[2]); // printed as 300
    System.out.println(numbers[3]); // printed as 400
    System.out.println(numbers[4]); // printed as 500
    System.out.println(size); // printed as 5
    
    // Array initialization by this description method is also effective
    int[] id = new int[]{1, 2, 3};

    System.out.println(id[0]); // printed as 1
    System.out.println(id[1]); // printed as 2
    System.out.println(id[2]); // printed as 3
    System.out.println(id.length); // prints 3
  }
}

When accessing outside the array element

I used to access the elements of the array using subscripts (indexes), When trying to access the elements outside the array, a compile error does not occur, but a runtime error (exception) occurs. For details, see Exception handling article.

Let’s take a light look here as well.

Main.java


class Main {
  public static void main(String[] args) {
    int[] id = {1, 2, 3, 4, 5}; // array has 5 elements

    // loop 6 times in the for statement = exceed the elements of the id array
    for(int i = 0; i <6; i++) {
      // output one by one
      System.out.println(id[i]);
    }
    System.out.println("I have finished printing all the contents of the id array.");

  }
}

The output result is

Terminal


1
2
3
Four
Five
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
        at Main.main(Main.java:195)

It was output as above.An ArrayIndexOutOfBoundsException exception has occurred. And I finished outputting all the contents of the id array. Is not displayed. When trying to access the array like this, if you are accessing outside the element, Be careful as an exception occurs and processing stops in the middle.

Declaration of 2D array

There is also a two-dimensional array that manages two subscripts (indexes) and a multidimensional array with more than that. This time, I will explain the two-dimensional array.

For a two-dimensional array, use two [] Declare data type [][] array name.

Main.java


class Main {
  public static void main(String[] args) {
    int[][] numbers; // Declaration of 2D array that can handle int type values

    // [][] can be after the array name.
    String strs[][]; // Declaration of 2D array that can handle String type values
  }
}

Instantiate a two-dimensional array

As in the case of a one-dimensional array, you need to secure a space for filling the declared array with values.

Main.java


class Main {
  public static void main(String[] args) {
    int[][] numbers; // Declaration of 2D array that can handle int type values
    String strs[][]; // Declaration of 2D array that can handle String type values

    // In an array with 3 elements, allocate an area with 4 elements for each element from numbers[0] to numbers[2]
    numbers = new int[3][4];

    // In an array with 2 elements, secure an area for 2 elements in each element of strs[0] to strs[1]
    strs = new String[2][2];
  }
}

Like a one-dimensional array, ** It is also possible to declare the array and secure the area at the same time. **

Main.java


class Main {
  public static void main(String[] args) {
    // Declare a 2D array that can handle int type values and secure the area
    int[][] numbers = new int[3][4];

    // Declare a 2D array that can handle String type values and secure the area
    String strs[][] = new String[2][2];
  }
}

It is also possible to secure only the area of the 1st dimension array. ` In that case, you can decide the number of elements in the second dimension later.

Main.java


class Main {
  public static void main(String[] args) {
    int[][] array; // Declaration of 2D array that can handle int type values
    array = new int[3][]; // allocate area for array with 3 elements

    array[0] = new int[5]; // first array of array can store 5 elements
    array[1] = new int[3]; // second array of array can store 3 elements
    array[2] = new int[4]; // 3rd array of array can store 4 elements

    // Same when array declaration and area allocation are done at the same time
    String[][] strs = new String[2][]; // Declare array of String type, secure area
    strs[0] = new String[6]; // The first array of strs can contain 6 elements
    strs[1] = new String[3]; // second array of strs can hold 3 elements
  }
}

In the case of a two-dimensional array, the number of elements cannot be changed later, and the number of elements must be an integer.

2D array subscript (index) and value storage

Like the one-dimensional array, the value is stored using the subscript (index).

Main.java


class Main {
  public static void main(String[] args) {
    int[][] numbers = new int[2][2]; // Declaration of 2D array that can handle int type values
    numbers[0][0] = 100;
    numbers[0][1] = 200;
    numbers[1][0] = 300;
    numbers[1][1] = 400;

    System.out.println(numbers[0][0]); // printed as 100
    System.out.println(numbers[0][1]); // printed as 200
    System.out.println(numbers[1][0]); // printed as 300
    System.out.println(numbers[1][1]); // printed as 400
  }
}

2D array initialization

Even in a two-dimensional array, You can declare an array, secure an area, and assign a value (initial value) all at the same time. (Initialization of array)

Similarly, enclose the value in {} and describe each element with a comma. Data type [][] array name = { {Initial value 1, initial value 2, initial value 3, initial value 4, initial value 5}, {Initial value 6, Initial value 7, Initial value 8, Initial value 9, Initial value 10} };

Also, use length to check the number of created elements. You can get the number of elements with array name.length;. To get the length of an array within that array, You can get the number of elements with array name [subscript (index)].length.

Main.java


class Main {
  public static void main(String[] args) {
    // Array declaration, area allocation, and value assignment can be done at once, just like a one-dimensional array.
    int[][] numbers = {
      {1, 2, 3, 4, 5},
      {6, 7, 8, 9, 10},
      {11, 12, 13},
      {16, 17}
    };
    System.out.println("numbers[0][4] value :" + numbers[0][4]); // numbers[0][4] value :5
    System.out.println("numbers[3][0] value :" + numbers[3][0]); // outputs numbers[3][0] value :16

    System.out.println("length of numbers :" + numbers.length); // length of numbers :4
    System.out.println("length of numbers[0] :" + numbers[0].length); // length of numbers[0] :5
    System.out.println("numbers[2] length :" + numbers[2].length); // number[2] length :3
    System.out.println("length of numbers[3] :" + numbers[3].length); // length of numbers[3] :2
  }
}

Example of how to use arrays

From here, I will show you how to easily use 1D and 2D arrays.

Sort in ascending order

Remember to import it first, as it uses the java.util.Arrays class. Click here for Oracle’s Arrays class

Main.java


import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    // Initialize numbers array (random order of integers inside)
    int[] numbers = {10, 1, 5, 6, 9};

    // Use sort method of Arrays class to sort in ascending order
    Arrays.sort(numbers);

    // output numbers array one by one
    for(int number: numbers) {
      System.out.print(number + ""); // printed as 1 5 6 9 10
    }
  }
}

The numbers that stored random integers can be sorted in ascending order by using the sort method.

Next, let’s sort the strings.

Main.java


import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    // Initialize the names array (random order of names inside)
    String[] names = {"tanaka", "abe", "suzuki", "maeda"};

    // Use the sort method of Arrays class to sort alphabetically
    Arrays.sort(names);

    // print the names array one by one
    for(String name :names) {
      System.out.print(name + ""); // abe maeda suzuki tanaka is output
    }
  }
}

The names that stored a random character string can be sorted in alphabetical order by using the sort method.

Get maximum and minimum values

Main.java


class Main {
  public static void main(String[] args) {
    // Initialize the 2D array numbers (the order of the integers inside is random)
    int[][] numbers = {
      {2, 5, 6, -10, 100, 3},
      {-1000, 1, 20},
      {999, 12, 300, 50}
    };


    // define max variable to hold maximum value
    int max = 0;
    // define a min variable to hold the minimum value
    int min = 0;


    // Look at the first dimension of the numbers array one by one
    for(int i = 0; i <numbers.length; i++) {

      // Go through the contents of numbers[0], numbers[1], numbers[2] one by onefor(int j = 0; j <numbers[i].length; j++) {

        // If there is a number greater than max among numbers[0], numbers[1], numbers[2]
        if(max <numbers[i][j]) {

          // Substitute that number into the max variable
          max = numbers[i][j];

        }

        // If there is a number less than min among numbers[0], numbers[1], numbers[2]
        if(min >numbers[i][j]) {

          // Assign that number to the min variable
          min = numbers[i][j];

        }

      }
    }

    System.out.println("Maximum value of numbers array :" + max); // Maximum value of numbers array :999 is output
    System.out.println("minimum value of numbers array :" + min); // minimum value of numbers array :-1000 is output

  }
}

The elements of the arrays are compared one by one using the for statement (I will write a separate article about the iteration process).

If there is a large number or a small number, the value is assigned to the maximum value max variable and minimum value min variable each time.

At the end

It’s easy, but I learned about arrays.

The array has a fixed number of elements, but there is also a List that is variable. I would like to cover that in another article.

Since multiple data can be used, there are many opportunities to use it. I want to keep it firmly.