Java几种类型数组的默认值

来源:互联网 发布:win10允许软件联网 编辑:程序博客网 时间:2024/05/14 12:30

无论是C语言还是Java都必不可少的使用到数组。

说起数组,就不得不说说数组的默认值。

之前一直不太明白这些的默认值到底是什么?碰到了索性都编了一下还是用事实说话,比较有利。

实验发现:

1、int类型定义的数组,初始化默认是0

2、String类型定义的数组,默认值是null

3、char类型定义的数组,默认值是0对应的字符

4、double类型定义的数组,默认值是0.0

5、float类型定义的数组,默认值是0.0

而且不仅仅是数组第一个元素有默认值,所有的数组的默认值和上面的规则一样

实验代码:

package com.xaut.cherry.niukewang0702;
/*
 * 几种类型的数组的默认值
 * */
public class ArrayInitialValue {


public static void main(String[] args) {
// TODO Auto-generated method stub
int [] intarray = new int [10];
for(int i = 0;i<intarray.length;i++){
System.out.println("int : "+intarray[i]);      //int类型定义的数组,初始化默认是0
}
System.out.println();
String [] stringarray = new String[10];
for(int i = 0;i<stringarray.length;i++){
System.out.println("String : "+stringarray[i]);   //String类型定义的数组,默认值是null
}
System.out.println();
char [] chararray = new char[10];
for(int i = 0;i<chararray.length;i++){
System.out.println("char : "+(int)chararray[i]);   //char类型定义的数组,默认值是0对应的字符
}
System.out.println();
double [] doublearray = new double[10];
for(int i = 0;i<doublearray.length;i++){
System.out.println("double : "+doublearray[i]);   //double类型定义的数组,默认值是0.0
}
System.out.println();
float [] floatarray = new float[10];
for(int i = 0;i<floatarray.length;i++){
System.out.println("float : "+floatarray[i]);   //float类型定义的数组,默认值是0.0
}


}


}

实验结果:




原创粉丝点击