Home >Java >JavaBase >How to implement array initialization in java

How to implement array initialization in java

coldplay.xixi
coldplay.xixiOriginal
2020-10-22 10:52:0248301browse

Java method to implement array initialization: 1. Dynamic initialization, format [data type [] array name = new data type [array length]]; 2. Static initialization, format [data type [] array name = new data type [ ]{element 1, element 2, element 3...}].

How to implement array initialization in java

How to implement array initialization in java:

1. Static initialization

2. Dynamic Initialization

format:

1. Dynamic initialization format:

数据类型 [ ] 数组名称 = new 数据类型[数组长度]

2. Static initialization format:

数据类型 [ ] 数组名称 = new 数据类型[ ]{元素1,元素2,元素3…}

3. Static Initialization omitted format:

数据类型 [ ] 数组名称 = {元素1,元素2,元素3…}

Dynamic initialization:

public class DynamicArray {
    public static void main(String[] args) {
        int i = 5;
        int[] arrayA = new int[5];//动态数组的标准分配
        arrayA[0] = 1;
        arrayA[1] = 2;
        arrayA[2] = 3;
        System.out.printf("%d\n%d\n%d\n", arrayA[0], arrayA[1], arrayA[2]);
        int[] arrayB;//动态数组分步分配
        arrayB = new int[i];
        arrayB[0] = 4;
        arrayB[1] = 5;
        arrayB[2] = 6;
        System.out.printf("%d\n%d\n%d\n", arrayB[0], arrayB[1], arrayB[2]);
    }
}

Static initialization:

public class StaticArray {
    public static void main(String[] args) {
        int[] arrayA = new int[]{10, 20, 30};//静态数组标准分配
        System.out.printf("%d\n%d\n%d\n", arrayA[0], arrayA[1], arrayA[2]);
        arrayA[0] = 20;
        System.out.printf("%d\n%d\n%d\n", arrayA[0], arrayA[1], arrayA[2]);
        char[] arrayB;
        arrayB = new char[]{'大', '来', '嘞'};
        System.out.printf("%c\n%c\n%c\n", arrayB[0], arrayB[1], arrayB[2]);//静态数组两步骤分配
        int[] arrayC = {30, 40, 50};// 静态数组省略式分配,注意省略不可以分两步骤
        System.out.printf("%d\n%d\n%d\n", arrayA[0], arrayA[1], arrayA[2]);
    }
}

Related free learning recommendations: javaBasic Tutorial

The above is the detailed content of How to implement array initialization in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn