数组的默认初始化
基于基本数据类型的变量创建的数组: byte short int long double float char boolean
对于基本数据类型为: byte short int long 初始化为 0
对于基本数据类型为: double float 默认的为 0.0 boolean
对于基本数据类型为:char 默认为 空格
对于基本数据类型为: boolean 默认为 false
对于引用类型的变量构成的数组而言,默认初始化值为 null 如下的以String为例
public class TestArray { public static void main(String[] args) { // 对于基本数据类型为: byte short int long 初始化为 0 int[] scores = new int[4]; scores[0] = 12; scores[2] = 12; for (int i = 0; i < scores.length; i++) { System.out.print(scores[i] + " ");// 12 0 12 0 } System.out.println(); byte[] scores1 = new byte[4]; scores1[0] = 12; scores1[2] = 12; for (int i = 0; i < scores1.length; i++) { System.out.print(scores1[i] + " ");// 12 0 12 0 } System.out.println(); // 对于基本数据类型为: double float 默认的为 0.0 boolean double[] scores2 = new double[4]; scores2[0] = 12; scores2[2] = 12; for (int i = 0; i < scores2.length; i++) { System.out.print(scores2[i] + " ");// 12.0 0.0 12.0 0.0 } System.out.println(); // 对于基本数据类型为:char 默认为 空格 char[] scores3 = new char[4]; for (int i = 0; i < scores3.length; i++) { System.out.print(scores3[i] + " ");// 空格 } System.out.println(); // 对于基本数据类型为: boolean 默认为 false boolean[] scores4 = new boolean[4]; for (int i = 0; i < scores4.length; i++) { System.out.print(scores4[i] + " ");// false false false false } //对于引用类型的变量构成的数组而言,默认初始化值为 null String[] strs = new String[4]; strs[0] = "AA"; strs[1] = "BB"; // strs[2] = "CC";//null strs[3] = "DD"; for (int i = 0; i < strs.length; i++) { System.out.print(strs[i]+" ");//AA BB null DD } } }
All that work will definitely pay off