java新手,这些基础知识一直记不住,所以就写出来加深记忆。一、数组的声明:Java数组有两种声明方式//数组的两种声明方式 int[] a; int b[];
二、数组的 初始化Java 数组有三种初始化方式:
静态初始化
//静态初始化 int[] array1 = {4,5,6};
用new声明,之后分别初始化数组中的每个元素,声明时需指定数组大小。
//用new声明,之后分别初始化数组中的每个元素 int[] array2 = new int[3]; array2[0] = 1; array2[1] = 2; array2[2] = 3;
用new声明的同时初始化,这种方式不能指定数组的大小,数组大小由初始化列表中数据个数决定。
//用new声明的同时初始化 int[] array3 = new int[]{1,2,3};
三、数组的遍历Java数组有两种遍历方式:
for遍历
//for循环遍历 System.out.print("for循环遍历数组:"); for(int i = 0; i < 3; i++){ System.out.print(" " + array1[i]); }
2、foreach遍历//foreach遍历数组 System.out.print("foreach循环遍历数组:"); for(int i: array2){ System.out.print(" " + i); }
四、基本数据类型对应数组中元素的默认值int数组中元素默认值是:0
double数组中元素默认值是:0.0
float数组中元素默认值是:0.0
char数组中元素默认值是:‘\0'boolean数组中元素默认值是:falseint[] iArray = new int[3]; double[] dArray = new double[3]; float[] fArray = new float[3]; char[] cArray = new char[3]; boolean[] bArray = new boolean[3]; System.out.println("int数组中元素默认值是:" + iArray[0]); System.out.println("double数组中元素默认值是:" + dArray[0]); System.out.println("float数组中元素默认值是:" + fArray[0]); System.out.println("char数组中元素默认值是:" + cArray[0]); System.out.println("boolean数组中元素默认值是:" + bArray[0]); System.out.println((cArray[0] == ' ' ? true: false)); System.out.println(cArray[0] == '\0' ? true: false);
输出如下:int数组中元素默认值是:0
double数组中元素默认值是:0.0
float数组中元素默认值是:0.0
char数组中元素默认值是:boolean数组中元素默认值是:false
false
true
欢迎各位大神批评指正。源代码如下:package array; public class ArrayTest { public static void main(String[] args){ int[] iArray = new int[3]; double[] dArray = new double[3]; float[] fArray = new float[3]; char[] cArray = new char[3]; boolean[] bArray = new boolean[3]; System.out.println("int数组中元素默认值是:" + iArray[0]); System.out.println("double数组中元素默认值是:" + dArray[0]); System.out.println("float数组中元素默认值是:" + fArray[0]); System.out.println("char数组中元素默认值是:" + cArray[0]); System.out.println("boolean数组中元素默认值是:" + bArray[0]); System.out.println((cArray[0] == ' ' ? true: false)); System.out.println(cArray[0] == '\0' ? true: false); //数组的两种声明方式 int[] a; int b[]; //静态初始化 int[] array1 = {4,5,6}; //用new声明,之后分别初始化数组中的每个元素 int[] array2 = new int[3]; array2[0] = 1; array2[1] = 2; array2[2] = 3; //用new声明的同时初始化 int[] array3 = new int[]{1,2,3}; //for循环遍历 System.out.print("for循环遍历数组:"); for(int i = 0; i < 3; i++){ System.out.print(" " + array1[i]); } System.out.println(); //foreach遍历数组 System.out.print("foreach循环遍历数组:"); for(int i: array2){ System.out.print(" " + i); } System.out.println(); } }