0
点赞
收藏
分享

微信扫一扫

数组的三种初始化方式

1.静态初始化

除了用new 关键字来产生数组以外,还可以直接在定义数组的同时就为数组元素分配空间并赋值

package com.yqq.app11;

/**
* @Author yqq
* @Date 2021/11/19 23:52
* @Version 1.0
*/
public class Test02 {
public static void main(String[] args) {
int[] a = {1,2,34,5};
Student[] sts = {new Student(23,"james"),new Student(24,"kobe")};
System.out.println(sts[1].getName());
System.out.println(a[1]);
}
}

2.动态初始化

数组定义与为数组元素分配空间并赋值的操作分开进行

package com.yqq.app11;

/**
* @Author yqq
* @Date 2021/11/19 23:57
* @Version 1.0
*/
public class Test03 {
public static void main(String[] args) {
int[] s = new int[10];
for (int i = 0; i < s.length; i++) {
s[i] = 2*i+1;
}
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
}
}

3.默认初始化

数组是引用类型,它的元素相当于类的实例变量,因此数组一经分配空间,其中的每个元素也被按照实例变量同样的方式被隐式初始化

int[] arr = new int[2];//默认值为0,0
boolean[] b = new boolean[2];//默认值为false,false
String[] str = new String[2];//默认值为null,null


举报

相关推荐

0 条评论