JAVA basics/Lesson 19th: how to create an array or JAVA Array
An array is a fixed-length container that contains the same type of data.
I. Declare an array:
Int [] a; declares an array variable.
[] Indicates that the variable is an array.
Int indicates that each element in the array is an integer.
A is the variable name.
However, this statement does not create arrays.
Sometimes it will be written as int a []; Which of the following is a pleasing question:
Public class HelloWorld {public static void main (String [] args) {// declare an array int [] ;}}2. Create an array:
Specify the length of the array when creating an array. New int [5]
Reference concept:
If a variable represents an array, for example, a is called a reference. It is different from the basic type: int c = 5; this is to assign a value of 5 to c.
Declare a reference to int [];
A = new int [5];
Let the reference a point to the array.
Public class HelloWorld {public static void main (String [] args) {// declare a reference int [] a; // create an array with a length of 5, and use reference a to point to the array a = new int [5]; int [] B = new int [5]; // when declaring, point to an array }}3. Access the array:
Public class HelloWorld {public static void main (String [] args) {int [] a; a = new int [5]; a [0] = 1; // subscript 0, represents the first number in the array a [1] = 2; a [2] = 3; a [3] = 4; a [4] = 5 ;}}Iv. array length:
The. length attribute is used to access the length of an array.
Array access subscript range is 0 to length-1
If the range is exceeded, an array subscript out-of-bounds exception occurs.
Public class HelloWorld {public static void main (String [] args) {int [] a; a = new int [5]; System. out. println (. length); // print the length of the array a [4] = 100; // subscript 4, essentially "5th", both the last a [5] = 101; // subscript 5, which is essentially "6th". Beyond the range, an array subscript out-of-bounds exception is generated }}
5. initialize the array:
1. Allocate space and assign values step by step:
Public class HelloWorld {public static void main (String [] args) {int [] a = new int [5]; // an array with a length of 5 is allocated, if no value is assigned, // is used as the int type array. The default value is 0 System. out. println (a [0]); // assign a value a [0] = 100; a [1] = 101; a [2] = 103; a [3] = 120; a [4] = 140 ;}}
2. Allocate space and assign values at the same time:
Public class HelloWorld {public static void main (String [] args) {// Method 1: assign a value to int [] a = new int [] {100,102,444,836,323 6} when allocating space }; // Statement 2: new int [] is omitted, and the result is the same as int [] B = {100,102,444,836,323 6}; // Statement 3: Allocate space at the same time, and the specified content // In this example, the length is 3 and the content is 5, causing conflicts // so if the array content is specified, you cannot set the length of the array at the same time. int [] c = new int [3] {100,102,444,836,323 6 };}}