大批

Java数组是存储同类型多个值的便捷方式,它们基于索引,方便数据管理。本文介绍Java数组的基本操作。

一、数组声明与创建

声明数组使用以下语法:

type[] arrayName; 

其中type是数组元素的数据类型(例如intString),arrayName是数组名称。 注意:声明仅定义数组的类型和名称,并未分配内存。

创建数组需要使用new关键字分配内存:

int[] numbers = new int[5]; 

这行代码创建一个名为numbers的数组,可以存储5个整数,默认值均为0。

二、数组元素访问与修改

使用索引访问数组元素,索引从0开始:

numbers[0] = 10; // 设置第一个元素为10
int firstElement = numbers[0]; // 获取第一个元素的值

修改元素值,直接将新值赋给指定索引即可:

numbers[0] = 20; // 将第一个元素修改为20

三、数组长度

使用.length属性获取数组长度:

int length = numbers.length; 

四、示例程序

以下程序演示数组的基本用法:

public class Main {
    public static void main(String[] args) {
        int[] marks = {96, 92, 65, 89, 93}; 
        System.out.println(marks.length); // 输出数组长度

        int i = 0;
        int total = 0;
    

while (i < marks.length) { System.out.println(marks[i]); // 输出每个元素的值 total += marks[i]; // 计算总和 i++; } System.out.println(total); // 输出总和 System.out.println(total / marks.length); // 输出平均值 } }

输出:

5
96
92
65
89
93
435
87