This chapter summarizes the basic syntax of Java arrays, shares it with new learning partners, and shares new knowledge to make progress together.
Article Directory
I. Introduction
Review the data type:
- (1) Basic type
byte short int long float double char boolean
- (2) Reference type
类 数组 接口 枚举 注解
- Variable : A piece of storage space in memory that stores constants.
- Features : One variable can only store one data, not multiple.
Need: Statistics to put all the java scores of 30 students in a class?
- Solution 1: Use variable storage, need to declare 30 variables: int java1 = 90; int java2 = 80;
- Solution 2: use array
2. Array
What is an array?
- The combination of data, more than one data, contains multiple data. An array is just a variable.
Array declaration and initialization declaration:
- Method 1 :
数据类型 [] 数组名
- Method 2 :
数据类型 数组名[]
initialization:
- The array in Java
必须先初始化
can only be used afterwards. The so-called initialization is to allocate memory space for the array elements in the array and assign initial values to each array element.
Distinguish between static initialization and dynamic initialization
- Static initialization
- During initialization, the programmer specifies the initial value of each array element, and the system calculates the array length.
语法:数组元素类型[] 数组名 = new 数组元素类型[]{元素0,元素1, };
可简写为:数组元素类型[] 数组名 = {元素0,元素1, };
- Note: any variable must have its own data type, arr here means the name of the array variable, int means the type of the elements in the array, int [] is the array type
- Note: The shorthand static initialization can only be completed by one statement, and cannot be divided into two statements.
/*
静态初始化:由我们指定元素的初始值,由系统计算长度或者元素的个数
*/
int[] arr = new int[]{1,56,76,87};
int[] arr1 = {1,56,76,87};
String[] arr2 = new String[]{"434","gfg","gjf545"};
String[] arr3 = {"434","gfg","gjf545"};
//Scanner[] arr4 =
char[] arr5 = new char[]{'2','g','*'};
char[] arr5 ={'2','g','*'};
- Dynamic initialization
- During initialization, the programmer only specifies the length of the array, and the system assigns initial values to the array elements
语法:元素类型[] 数组名 = new 元素类型[元素个数或者数组长度];
- The system assigns rules for initial values as follows:
- a. The integer type is 0
- b. Floating point is 0.0
- c. The character type is '\ u0000' (different system platforms display different results)
- d. Boolean type is false
- e. Reference type is null
/*
动态初始化:初始化时由程序员指定数组的长度,系统负责分配元素的初始值
*/
int[] array1 = new int[5];//0
String[] array2 = new String[3];//null
char[] array3 = new char[10];//\u0000
Note: a. When initializing an array, do not use static initialization and dynamic initialization at the same time, that is, do not specify the length of the array and assign an initial value to each array element when performing array initialization.
Three. The use of arrays
(1) Access the specified element by subscript
- note:
- ① Java array index (subscript, corner index) starts from 0, the maximum length of the array subscript is -1
- ② Do not exceed the index range, if an exception occurs java.lang.ArrayIndexOutOfBoundsException (index out of bound exception)
//使用静态初始化的方式定义一个数组
//数组中可以存放重复数据
int[] arr1 = new int[]{2,65,76,83,32,5,5};
//1.访问数组中的元素
//格式:数组名称[下标] 表示获取指定下标所对应的值
//需求:获取下标3对应的元素
int num1 = arr1[3];
System.out.println(num1);//83
System.out.println(arr1[3]);//83
(2) 2.3.2 Get the number of array elements
- In Java, all arrays provide a length property, through which you can access the length of the array or the number of elements in the array
//2.获取数组中的元素个数或者数组的长度
//格式:数组名称.length; int len = arr1.length;
System.out.println("数组arr1的长度为:" + len);
(3) Modify the values of array elements
//3.修改数组元素的值int num2 = arr1[6];
System.out.println(num2);//
//格式:数组名称[下标] = 被修改之后的值
//注意:不管是静态初始化还是动态初始化,都可以采用这种方式修改元素的值arr1[6] = 100;
System.out.println(arr1[6]);//100
(4) Traverse the array
- Access each element in the array in turn to get the element value corresponding to each subscript
- Method 1: Simple for loop
- Method 2: Subscript cannot be used for enhanced for loop
public class Demo {
public static void main(String[] args) {
int[] arr1 = new int[]{2,65,76,83,32,5,5};
//4.遍历数组
int n0 = arr1[0];
int n1 = arr1[1];
int n2 = arr1[2];
int n3 = arr1[3];
int n4 = arr1[4];
int n5 = arr1[5];
int n6 = arr1[6];
//1>简单for循环
//i表示下标,0~arr1.length
for(int i = 0;i < arr1.length;i++) {
int n = arr1[i];
System.out.println(n);
}
/*
2>增强for循环【foreach】JDK1.5之后新增的
优点:用于遍历数组和集合,无需通过数组下标,就可以直接访问数组或者集合中的元素 语法:
for(元素数据类型 变量名:数组名称) { System.out.println(变量名);
}
*/
//底层工作原理:根据下标获取数组元素
for(int num : arr1) {
System.out.println("增强for循环的结果:" + num);
}
/*
两种遍历方式的选择:不需要知道下标,只需要获取元素值,则采用增强for循环
*/
//需求:打印下标为偶数的元素值【只能采用简单for循环】
for(int i = 0;i < arr1.length;i++) {
if(i % 2 == 0) {
int n = arr1[i];
System.out.println(n);
}
}
}
}
Case exercise: keyboard to enter the student's java score, and save the score in the array, and then calculate the total score and average score?
public class Demo {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("请输入班级人数");
int count=input.nextInt();
int[] score=new int[count];
for (int i = 0; i < score.length; i++) {
System.out.println("请输入第"+(i+1)+"个人的java成绩");
score[i]=input.nextInt();
}
System.out.println(" ");
int sum=0;//总分
double avg=0;//平均分
for (int n : score) {
sum=sum+n;
}
avg=(double)sum/count;
System.out.println("总分是:"+sum);
System.out.println("平均分是:"+avg);
}
}
Four. Array memory allocation
java memory:
- Stack :
存储基本类型数据
and引用类型的地址
, features : advanced and late, generally less space, faster access - Heap :
存储引用类型数据,
Features : Larger space and relatively slow storage speed - Method area : store string constant pool, static data, code and class metadata
Arrays are reference types. Array reference variables are just a reference. This reference variable can point to any valid memory space. Only when this reference points to a valid space can you manipulate the elements in the real array by reference.
Conclusion : The reference variable of the array is stored in the stack space, and the real array data is stored in the heap space.
public class Demo {
public static void main(String[] args) {
//图1 使用静态初始化的方式初始化一个数组a
int[] a = {5,7,20};
System.out.println("a的长度为:" + a.length);//3
int num =8;
System.out.println("num:"+num);
//图2
int[] b=new int[4];
System.out.println("b的长度是:"+b.length);
b=a;
System.out.println("b的长度是:"+b.length);
System.out.println(b); //输出的是地址值
}
}
Extension: common exceptions when using arrays
1> Array out-of-bounds exception : When ArrayIndexOutofBoundsException
appears: This error occurs when a non-existent subscript is used 0 ~ length-1
2> Null pointer exception : NullPointerException
timing: When the reference variable of the array is assigned null, this reference is also used in the following code
-
The best investment is in yourself
-
2020.04.16 记录辰兮的第56篇博客