Java基本语法-3(数组)
本章我们将详细介绍java中的数组包括一维数组、一维数组的内存结构。
一、数组的初始化以及默认值
格式:数据类型 [] 名称 = new 数据类型[初始大小]
基本数据类型的数组
1,对于byte、short、int、long:创建数组后,默认值为0
例如: int [] scores = new int[4];
scores [0] = 115;
scores [2] = 100;
for(int i = 0; i < scores.length; i++){
System.out.println(scores[i]);
}
输出结果:115 0 100 0
2,对于float、double:创建数组后,默认值为0.0
例如: double[] f= new double[4];
f[0] = 1.2F;
f[2] = 1.5F;
for(int i = 0; i < f.length; i++){
System.out.println(f[i]);
}
输出结果:1.2 0.0 1.5 0.0
3,对于char:创建数组后,默认值为空格
例如: char[] c= new char[4];
c[0] = 'a';
c[2] = 'b';
for(int i = 0; i < c.length; i++){
System.out.println(c[i]);
}
输出结果:a b
4,对于boolean:创建数组后,默认值为false
例如: boolean[] b= new boolean[4];
for(int i = 0; i < b.length; i++){
System.out.println(b[i]);
}
输出结果:false false false false
5,对于引用类型的变量:创建数组后,默认值为null,以String为例
例如: String[] strs= new String[4];
for(int i = 0; i < strs.length; i++){
System.out.println(strs[i]);
}
输出结果:null null null null
二、一维数组的内存结构
栈:用来存放局部变量、对象引用(先进后出)
堆:存放new出来的东西(先进先出)
例子:
int [] score = new int [4];
score [0] = 89;
score [3] = 90;
当执行第一句的时候,先将strs变量放到栈中,并同时在堆中占用4个位置的内存,strs和内存通过地址值进行关联,并初始化值为0;
如图:

执行赋值后替换原索引位置的值

通过以上int数组的实例详细讲解了数组的内存结构。

浙公网安备 33010602011771号