[Introduction to Java] About array operations (1D array, 2D array declaration, instantiation, initialization and use)

Purpose

For those who have just started learning programming including the Java language, and those who have already learned it, for review This time I'm writing to learn about ** arrays **.

[Introduction to Java Table of Contents] -Variables and typesType conversion -Variable Scope -String operation ・ Array operation ← 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 the module (in preparation) -Exception handlingAbout lambda expressionAbout Stream API

What is an array?

A variable is a container that holds one value data for one variable (Click here for variables).

By using an array, you can manage multiple data of the same data type in one array. ``

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

You can also easily sort the data in the array and get the largest value.

Declaration of one-dimensional array

When creating an array, it is necessary to first decide the data type of what kind of value to handle like a variable, give it a name, and declare it.

Declare the data type [] array name.

Main.java


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

    // []Can be after the array name.
    String names[]; //Declaration of an array that can handle String type values
  }
}

Instantiation of one-dimensional array

It is necessary to secure an area for how much the value is packed in the declared array. Determine the size of the area to be secured by new [number of elements].

Main.java


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

    numbers = new int[50]; //Reserve an area to store 50 values in the numbers array
    names = new String[3]; //Reserve an area to store 3 values in the name array
  }
}

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

Main.java


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

** Please 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, then the number of elements after that will be fixed at 5 all the time.

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

Storage of subscripts (indexes) and values in one-dimensional arrays

The array is declared and instantiated and ready to store the values. Use the subscript (index) to assign a value to an array. Subscripts (indexes) are serial numbers assigned to each element of the array, starting at 0.

Main.java


class Main {
  public static void main(String[] args) {
    int[] numbers = new int[5]; //Define a numbers array that can store 5 elements of int type
    numbers[0] = 100; //First, 100
    numbers[1] = 200; //Second, 200
    numbers[2] = 300; //Third, 300
    numbers[3] = 400; //Fourth, 400
    numbers[4] = 500; //Fifth, 500
  }
}

Subscripts (indexes) are also used to access each element of the array.

Main.java


class Main {
  public static void main(String[] args) {
    int[] numbers = new int[5]; //Define a numbers array that can store 5 elements of int type
    numbers[0] = 100; //First, 100
    numbers[1] = 200; //Second, 200
    numbers[2] = 300; //Third, 300
    numbers[3] = 400; //Fourth, 400
    numbers[4] = 500; //Fifth, 500

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

Initialization of one-dimensional array

Up to the above, array declaration, area allocation, and value (initial value) assignment were performed step by step.

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

Enclose the value in {} and describe each element separated by commas. Data type [] Array name = {Initial value 1, Initial value 2, Initial value 3, Initial value 4, Initial value 5};

Also, use lengthto find out how manyelements you have created. 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]); //Output as 100
    System.out.println(numbers[1]); //Output as 200
    System.out.println(numbers[2]); //Output as 300
    System.out.println(numbers[3]); //Output as 400
    System.out.println(numbers[4]); //Output as 500
    System.out.println(size); //Is output as 5
    
    //Array initialization using this description method is also effective.
    int[] id = new int[]{1, 2, 3};

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

When accessing outside the elements of the array

I used to use subscripts (indexes) to access the elements of the array, When trying to access outside the elements of an array, I don't get a compile error, but I get a run-time error (exception). For more information, see Exception Handling Articles (https://qiita.com/morioheisei/items/d25d2b67e7530c1aab9d).

Let's take a quick look here as well.

Main.java


class Main {
  public static void main(String[] args) {
    int[] id = {1, 2, 3, 4, 5}; //The number of elements in the array is 5

    //Turn the loop 6 times with the for statement=Exceeding elements of id array
    for(int i = 0; i < 6; i++) {
      //Output one by one
      System.out.println(id[i]);
    }
    System.out.println("I finished outputting all the contents of the id array.");

  }
}

The output result is

Terminal


1
2
3
4
5
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 you try to access the array like this, if you are accessing outside the element, Be careful as an exception will occur and processing will stop in the middle.

Declaration of a two-dimensional array

There are also two-dimensional arrays that manage two subscripts (indexes), and more multidimensional arrays. This time, I will explain the two-dimensional array.

In a two-dimensional array, use two [] to Declare the data type [] [] array name.

Main.java


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

    // [][]Can be after the array name.
    String strs[][]; //Declaration of a two-dimensional array that can handle String type values
  }
}

Instantiation of a two-dimensional array

As in the case of a one-dimensional array, it is necessary to secure an area for how much the declared array should be filled with values.

Main.java


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

    //An array with three elements, numbers[0]From numbers[2]Secure an area with 4 elements for each element of
    numbers = new int[3][4];

    //An array with two elements, strs[0]From strs[1]Secure an area with two elements for each element of
    strs = new String[2][2];
  }
}

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

Main.java


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

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

It is also possible to secure only the area of the `first 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 a two-dimensional array that can handle int type values
    array = new int[3][]; //Reserve an area for an array with three elements

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

    //The same applies when declaring an array and securing an area at the same time.
    String[][] strs = new String[2][]; //Declaration of String type array, allocation of area
    strs[0] = new String[6]; //The first array of strs can store 6 elements
    strs[1] = new String[3]; //The second array of strs can store three elements
  }
}

Even 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.

Storage of subscripts (indexes) and values in a two-dimensional array

Values are stored using subscripts (indexes) in the same way as one-dimensional arrays.

Main.java


class Main {
  public static void main(String[] args) {
    int[][] numbers = new int[2][2]; //Declaration of a two-dimensional 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]); //Output as 100
    System.out.println(numbers[0][1]); //Output as 200
    System.out.println(numbers[1][0]); //Output as 300
    System.out.println(numbers[1][1]); //Output as 400
  }
}

Initialization of 2D array

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

Similarly, enclose the value in {} and describe each element separated by commas. 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 lengthto find out how manyelements you have created. You can get the number of elements with array name.length;. To get the length of the array in 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) {
    //As with a one-dimensional array, it is possible to declare an array, secure an area, and assign values at once.
    int[][] numbers = {
      {1, 2, 3, 4, 5},
      {6, 7, 8, 9, 10},
      {11, 12, 13},
      {16, 17}
    };
    System.out.println("numbers[0][4]The value of the: " + numbers[0][4]); // numbers[0][4]The value of the:Is output as 5
    System.out.println("numbers[3][0]The value of the: " + numbers[3][0]); // numbers[3][0]The value of the:Is output as 16

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

An example of how to use an array

From here, I will introduce a simple usage of 1D array and 2D array.

Sort in ascending order

Remember to import first as we will be using 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 the numbers array (the order of the integers in it is random)
    int[] numbers = {10, 1, 5, 6, 9};

    //Sort in ascending order using the sort method of the Arrays class
    Arrays.sort(numbers);

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

Numbers, which stores 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 (the order of the names in it is random)
    String[] names = {"tanaka", "abe", "suzuki", "maeda"};

    //Sort alphabetically using the sort method of the Arrays class
    Arrays.sort(names);

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

Names, which contained random character strings, can be sorted alphabetically by using the sort method.

Get the maximum and minimum values

Main.java


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


    //Define max variable to put the maximum value
    int max = 0;
    //Define a min variable to put 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++) {

      // numbers[0]、numbers[1]、numbers[2]Look at the contents of, one by one
      for(int j = 0; j < numbers[i].length; j++) {

        // numbers[0]、numbers[1]、numbers[2]If there is a number larger than max in
        if(max < numbers[i][j]) {

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

        }

        // numbers[0]、numbers[1]、numbers[2]If there is a number smaller than min in
        if(min > numbers[i][j]) {

          //Substitute that number for the min variable
          min = numbers[i][j];

        }

      }
    }

    System.out.println("Maximum value in the numbers array: " + max); // Maximum value in the numbers array:Output as 999
    System.out.println("Minimum value in the numbers array: " + min); // Minimum value in the numbers array: -Output as 1000

  }
}

The elements of the array are compared one by one using the for statement (a separate article will be described for iterative processing).

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

At the end

It's easy, but I learned about arrays.

Arrays have a fixed number of elements, but there is also a variable List. 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 hold it firmly.

Recommended Posts

[Introduction to Java] About array operations (1D array, 2D array declaration, instantiation, initialization and use)
Java variable declaration, initialization, and types
[Introduction to Java] About lambda expressions
[Java beginner] About initialization of multidimensional array
[Introduction to Java] Variable declarations and types
[Java] How to use FileReader class and BufferedReader class
[Introduction to Java] About type conversion (cast, promotion)
[Java] Introduction to Java
Introduction to java
[Java] How to use Calendar class and Date class
Solving with Ruby and Java AtCoder ABC129 D 2D array
Java variable declaration, initialization, data type (cast and promotion)
[Java] Convert JSON to Java and Java to JSON-How to use GSON and Jackson-
Gzip-compress byte array in Java and output to file
Java, about 2D arrays
[Java Silver] About initialization
About Java Array List
Introduction to java command
Introduction to Effective java by practicing and learning (Builder pattern)
How to call and use API in Java (Spring Boot)
Reasons to use Servlet and JSP separately in Java development
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
Convert 2D array to csv format with Java 8 Stream API
A story about misunderstanding how to use java scanner (memo)
[Java] How to use Map
[Java] How to use Map
How to use java Optional
About Java variable declaration statements
[Java] How to use Optional ②
Java class definition and instantiation
[Java] How to use removeAll ()
[Java] Introduction to lambda expressions
[Java] How to use string.format
[Java] About String and StringBuilder
How to use Java Map
How to use Java variables
[Java] Introduction to Stream API
About Java Packages and imports
[Java] Convert ArrayList to array
[Java] How to use Optional ①
How to initialize Java array
[Introduction to rock-paper-scissors games] Java
About TestSize advocated by Google and how to realize TestSize by Java and Maven
Java SE Bronze Exam Number: 1Z0-818 (Data Declaration and Use) (October 2020)
[Java] Shallow copy and deep copy when converting an array to List
About the relationship between the Java String equality operator (==) and initialization. Beginners
[Introduction to Java] About exception handling (try-catch-finally, checked exception, unchecked exception, throws, throw)
Introduction to Scala from a Java perspective, decompiled and understood (basic)