java数组使用 二 数组的三种初始化

package array;

/**
 * 数组的三种初始化
 */
public class Demo02 {
    public static void main(String[] args) {
        test();

        test2();
    }

    public static void test2() {
        int[] a = {1, 2, 3, 4, 5, 67, 8, 9, 12, 123, 45, 78, 9, 546};

        int max = a[0];
        for (int i = 1; i < a.length; i++) {
            if (a[i] > max) {
                max = a[i];
            }
        }
        System.out.println("max" + max);//max546
    }

    public static void test() {
//        静态初始化
        int[] a = {1, 23, 3, 4, 5, 6, 7, 8, 9, 10};

        System.out.println(a[0]);//1

//        打印所有数组元素
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + "	");//1	23	3	4	5	6	7	8	9	10

        }
        System.out.println();
        System.out.println("============");
//        计算所有元素和

        int sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        System.out.println("sum:" + sum);//sum:76

//        查找最大元素

        int max = a[0];
        for (int i = 1; i < a.length; i++) {
            if (a[i] > max) {
                max = a[i];
            }
        }
        System.out.println("max:" + max);//max:23

//        引用类型
//        Man[] mans={new Man(),new Man()};


//    动态初始化
        int[] i = new int[10];
        i[0] = 10;
        System.out.println(i[0]);//10
    }
}

运行结果

原文地址:https://www.cnblogs.com/d534/p/15077958.html