[Java] How to create a Java array

2 minute read

3 steps to create an array

Creating an array requires three steps.

  1. Declare array variable
  2. Create array elements
  3. Assign value

As an image

  1. Make a big box (array variable)
  2. Make a partition (element of array) in the box
  3. Put a thing (value) in the partition

Such a place.

1. Declare array variable

To declare an array variable, write as follows.

Array element data type [] Array variable name;

The data type of the array element is the data type of the element to be assigned in the array. Int[] for integers, double[] for decimals, String[] for strings.

Basically, the variable name of the array is the English plural form that represents the contents of the array. If the contents of the array is the number of test scores, scores, if it is a character string of colors, colors etc.

Example: Defining an array of numbers, numbers

// Since it is an integer, the data type is int, and the data type is defined by adding [] after it.
int[] numbers;

2. Create element

To assign an element, describe as follows.

Array variable name = new element data type [number of elements];

Create an array element for the variable declared earlier.

The data type of the element is the same as the data type when the variable was declared. The number of elements is the number of values you want in the array.

Example: Substituting 3 elements into the array numbers defined earlier

// numbers is an array of integers so the data type is int
// There are 3 elements, so the number of elements is [3]
numbers = new int[3];

3. Assign value

To assign a value to the array, write as follows.

Array variable name [index number] = value to assign;

Example: Substituting integers 10, 20, 30 into numbers

// Note that the index number starts from 0
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

After creating the elements of the array, if no value is entered, the value is automatically assigned according to the data type when compiling. (0 for int, null for String, etc.)

Create array and assign value together

The array is created by following the above 3 steps.

Example: Creating an array of integer numbers and assigning integers 10, 20, 30

// declare variables
int[] numbers;

// create an element
numbers = new int[3];

// assign a value
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

However, these can also be described collectively as follows.

Array element data type [] Array variable name = {value1, value2, value3, ...};
// Example: Create an array of integer numbers and assign integers 10, 20, 30
int[] numbers = {10, 20, 30};