Home  >  Article  >  Java  >  What are the three ways to initialize an array in java?

What are the three ways to initialize an array in java?

王林
王林forward
2020-06-01 15:34:196125browse

What are the three ways to initialize an array in java?

Three initialization methods:

1. Static initialization: create and assign value

2. Dynamic initialization: create first and then assign value

3. Default initialization: If no value is assigned after creation, the default value of the corresponding data type will be assigned

(Video tutorial recommendation: java video)

Let’s take a look Here’s the specific code:

public class Test3 {
    public static void main(String[] args) {
        // 1、声明数组
        int[] array = null;
        // 2、创建数组
        array = new int[10];
        // 3、给数组元素中赋值
        for (int i = 0; i <array.length ; i++) {
            array[i] = i;
        }

        // 1、静态初始化:创建 + 赋值
        int[] array2 = {0,1,2,3};
        // 2、动态初始化:先创建再赋值
        int[] array3 = new int[10];
        for (int i = 0; i < array3.length ; i++) {
            array3[i] = i;
        }
        // 3、默认初始化
    }
}

Recommended tutorial: java entry program

The above is the detailed content of What are the three ways to initialize an array in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete