JAVA Getting Started Tutorial--Array

1. The concept of array
An array is an ordered collection of data of the same type. Among them, each piece of data is called an element, and each element can be passed through a
Index (subscript, starting from 0) to access.

2. Characteristics of arrays
The length is fixed. Once an array is created, its size cannot be changed.
Array types can be any data type, including primitive types and reference types.
The types of its elements must be the same type, mixed types are not allowed.
Array variables are reference types, and arrays are also objects, and the elements in the array are equivalent to the properties of the object!
3 How to declare an array
3.1 Method 1
type[ ] arr_name;
3.2 Method 2
type arr_name[ ];
Note: It is not instantiated when it is declared

When declaring an array he is not actually created

4 Create an array
4.1 Create a basic type one-dimensional array
public class Test {
public static void main(String args[]) {
int[] a; // declare array;
a = new int[10]; // allocate space for the array;
for (int i = 0; i < 10; i++) {
a[i] = i ;//Assign values to the array elements; the array is an object, and the elements in the array are the properties of the object
System.out.println(a[i]);
}
}
}
The result is as follows:

insert image description here

4.2 Creating an array of reference types
class Student {
private int age;
private int id;

public Student(int id, int age) {
super();
this. age = age;
this.id = id;
}
}

public class Test {
public static void main(String[] args) {
Student[] students; //declare reference type array;
students = new Student[10]; //Allocate space for the reference type array;
Student s1 = new Student(1, 11);
Student s2 = new Student(2, 22);
students[0] = s1;//Assign values to reference type array elements;
students[1] = s2;//Assign values to reference type array elements;
}
}
5 initialization
5.1 Static initialization
int [ ] a = { 1, 2, 3 };//Static initialization of basic type arrays;
Student[ ] student= { new Student(1, 1), new Student(2, 2) };// Static initialization reference type array;
5.2 Dynamic initialization
int[ ] a = new int[2];//Dynamically initialize the array, allocate space first;
a[0]=1;//Assign a value to the array element;
a[1]=1;//Assign a value to the array element;
5.3 Default initialization
int a[ ] = new int[2];
boolean[ ] b = new boolean[2];
String[ ] s = new String[2];

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us