数组定义格式
1.1数组概述

一次性声明大量的用于存储数据的变量
要存储的数据通常都是同类型数据,例如:考试成绩
1.2什么是数组
数组(array)是一种用于存储多个相同类型数据的存储模型
1.3数组的定义格式
格式一:数据类型[] 变量名
范例: int[] arr
定义了一个int类型的数组,数组名是arr
格式二:数据类型 变量名[]
范例:int arr[]
定义了一个Int类型的变量,变量名是arr数组
数组初始化之动态初始化
2.1数组初始化概述
java中的数组必须先初始化,然后才能使用
所谓初始化,就是为数组中的数组元素分配内存空间,并为每个数组元素赋值
2.2数组初始化方式
动态初始化
静态初始化
2.3动态初始化
动态初始化:初始化只指定数组长度,由系统为数组分配初始值
格式:数据类型[] 变量名=new 数据类型[数组长度]
范例: int[] arr = new int[3];
public class ScannerDemo {
public static void main(String[] args) {
int[] arr=new int[3];
/*
左边:
int:说明数组中的元素类型是int类型
[]:说明这是一个数组
arr:这是数组的名称
右边:
new:为数组申请内存空间
int:说明数组中的元素类型是int类型
[]:说明这是一个数组
3:数组长度,其实就是数组中的元素个数
* */
}
}
数组元素访问
3.1数组元素访问
数组变量访问方式
格式:数组名
数组内部保存的数据的访问方式
格式:数组名[索引]
索引是数组中数据的编号方式
作用:索引用于访问数组中的数据使用,数组名[索引]等同于变量,是一种特殊的变量名
特征1:索引从0开始
特征2:索引是连续的
特征3:索引逐一增加,每次加1
public class ScannerDemo {
public static void main(String[] args) {
int[] arr=new int[3];
/*
左边:
int:说明数组中的元素类型是int类型
[]:说明这是一个数组
arr:这是数组的名称
右边:
new:为数组申请内存空间
int:说明数组中的元素类型是int类型
[]:说明这是一个数组
3:数组长度,其实就是数组中的元素个数
* */
// 输出数组名
System.out.println(arr);
//输出数组中的元素
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
}
}
内存分配
4.1Java中内存分配
Java程序在运行时,需要在内存中分配内存空间,为了提高运算效率,就对空间进行了不同区域的划分
因为每一片区域都有特定的处理数据方式和内存管理方式




栈内存:存储局部变量
定义在方法中的变量,例如:arr
使用完毕,立即消失
堆内存:存储
数组在初始化时,会为存储空间添加默认值
整数:0
浮点数:0.0
布尔:false
字符:空字符
引用数据类型:null
每一个new出来的东西都有一个地址值
使用完毕,会在垃圾回收器空闲时被回收

4.2数组内存图(单个数组)


4.3数组内存图(多个数组)


4.4数组内存图(多个数组指向相同)


数组初始化之静态初始化
5.1数组初始化之静态初始化
静态初始化:初始化时指定每个数组元素的初始值,由系统决定数组长度
格式:数据类型[] 变量名=new 数据类型[]{数据1,数据2,数据3,...};
范例:int[] arr=new int[]{1,2,3};
简化格式:数据类型[] 变量名={数据1,数据2,数据3,......};
范例:int[] arr={1,2,3};
public class ScannerDemo {
public static void main(String[] args) {
//定义数组
int[] arr={1,2,3};
//输出数组名
System.out.println(arr);
//输出数组中的元素
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
}
}
数组操作的两个常见小问题
6.1数组操作的两个常见小问题
索引越界
ArrayIndexOutOfBoundsException
访问了数组中不存在的索引对应的元素,造成索引越界问题


空指针异常
访问的数组已经不再指向堆内存的数据,造成空指针异常

null:空值,引用数据类型的默认值,表示不指向任何有效对象
NullPointerException
数组常见操作
7.1遍历

public class ScannerDemo {
public static void main(String[] args) {
int[] arr={11,22,33,44,55};
for (int x=0;x<5;x++){
System.out.println(arr[x]);
}
}
}
7.2获取数组元素数量

格式:数组名.length
范例:arr.length
public class ScannerDemo {
public static void main(String[] args) {
int[] arr={11,22,33,44,55};
for (int x=0;x<arr.length;x++){
System.out.println(arr[x]);
}
}
}
遍历通用格式
int[] arr={......};
for (int x=0;x<arr.length;x++){
arr[x]
}
7.3获取最值

public class ScannerDemo {
public static void main(String[] args) {
//定义数组
int[] arr={12,45,98,73,60};
//定义一个变量,用于保存最大值
//取数组中的第一个数据作为变量的初始值
int max= arr[0];
//与数组中剩余的数据逐个比对,每次比对将最大值保存到变量中
for (int x=1;x<arr.length;x++){
if (arr[x]>max){
max=arr[x];
}
}
//循环结束后打印变量的值
System.out.println("max:"+max);
}
}