java各种数据类型的数组元素的默认值

时间:2022-05-10 09:59:48
public class DataTypeDefaultValue {
    public static void main(String[] args) {
        // string类型数组的默认值null
        // 对于引用类型的属性的默认值是null,如String类型
        System.out.println("查看String类型中数组的默认值:");
        String[] str = new String[4];
        str[0] = "aa";
        str[1] = "bb";
        str[2] = "cc";
        for (int i = 0; i < 4; i++) {
            System.out.println(str[i]);
        }
        // 对于short,int,long,byte而言,创建数组的默认值是0
        System.out.println("查看int类型数组的默认值:");
        int[] score = new int[4];
        score[0] = 90;
        score[1] = 89;
        score[2] = 34;
        for (int i = 0; i < score.length; i++) {
            System.out.println(score[i]);
        }
        System.out.println("查看short类型数组的默认值:");
        short[] score1 = new short[4];
        score1[0] = 90;
        for (int i = 0; i < score1.length; i++) {
            System.out.println(score1[i]);
        }
        System.out.println("查看long类型数组的默认值:");
        long[] score2 = new long[4];
        score2[0] = 90;
        for (int i = 0; i < score2.length; i++) {
            System.out.println(score2[i]);
        }
        System.out.println("查看byte类型数组的默认值:");
        byte[] score3 = new byte[4];
        score3[0] = 90;
        for (int i = 0; i < score3.length; i++) {
            System.out.println(score3[i]);
        }
        // 对于float double而言,默认值是0.0
        System.out.println("查看float类型数组的默认值:");
        float[] score4 = new float[4];
        score4[0] = 23;
        for (int i = 0; i < score4.length; i++) {
            System.out.println(score4[i]);
        }
        System.out.println("查看double类型数组的默认值:");
        double[] score5 = new double[4];
        score5[0] = 45;
        for (int i = 0; i < score5.length; i++) {
            System.out.println(score5[i]);
        }
        // 对于char类型
        // char类型数组的默认值是空格
        System.out.println("查看char类型数组的默认值:");
        char[] ch = new char[4];
        ch[0] = 'p';
        for (int i = 0; i < ch.length; i++) {
            System.out.println(ch[i]);
        }
        // 对于boolean类型的数组默认值
        // boolean类型数组的默认值是false
        System.out.println("查看boolean数组的默认值:");
        boolean[] b = new boolean[4];
        b[0] = true;
        for (int i = 0; i < b.length; i++) {
            System.out.println(b[i]);
        }
        /// 引用类型数组的默认值是null
        class Person {
        }
        System.out.println("查看引用类型的数组默认值:");
        Person[] p = new Person[4];
        for (int i = 0; i < p.length; i++) {
            System.out.println(p[i]);
        }
    }
}

运行结果:

查看String类型中数组的默认值:
aa
bb
cc
null
查看int类型数组的默认值:
90
89
34
0
查看short类型数组的默认值:
90
0
0
0
查看long类型数组的默认值:
90
0
0
0
查看byte类型数组的默认值:
90
0
0
0
查看float类型数组的默认值:
23.0
0.0
0.0
0.0
查看double类型数组的默认值:
45.0
0.0
0.0
0.0
查看char类型数组的默认值:
p