①创建数组的方式3种
①第1种方法
public class MyTest {
public static void main(String[] args){
//method 1
int[] array=new int[6];
int aa=array[4];
System.out.print(aa);
}
}
output:0
②第2种方法
public class MyTest {
public static void main(String[] args){
//method 2
int[] array={1,2,3,4,5};
System.out.print(array[2]);
}
}
output:3
③第3种方法,以及判断数组下标是否越界
public class MyTest {
public static void main(String[] args){
//method 2
int[] array=new int[]{1,2,3,4,5};
System.out.print(array[2] + "\n");
int m=0;
boolean length=isLength(m,array);
if(length){
System.out.print(array[m]);
}else{
System.err.print("array index is out of bound");
}
}
//判断数组下标是否越界
public static boolean isLength(int m,int array[]){
boolean flag=false;
int length=array.length;
if(m
flag=true;
return flag;
}
}
output:
3
1
②各种类型数组元素的默认值
①int
int [] intarray = new int [10];
for(int i = 0;i
System.out.println("int : "+intarray[i]); //int类型定义的数组,初始化默认是0
}
②string
String [] stringarray = new String[10];
for(int i = 0;i
System.out.println("String : "+stringarray[i]); //String类型定义的数组,默认值是null
}
③char
char [] chararray = new char[10];
for(int i = 0;i
System.out.println("char : "+(int)chararray[i]); //char类型定义的数组,默认值是0对应的字符
}
④double
double [] doublearray = new double[10];
for(int i = 0;i
System.out.println("double : "+doublearray[i]); //double类型定义的数组,默认值是0.0
}
⑤float
float [] floatarray = new float[10];
for(int i = 0;i
System.out.println("float : "+floatarray[i]); //float类型定义的数组,默认值是0.0
}