package com.kuangsheng.Array; public class ArrayDemo01 { public static void main(String[] args) { int [] nums; nums = new int[5];//等同于:int []nums = new int[5]; nums[0] = 1; nums[1] = 2; nums[2] = 3; nums[3] = 4; nums[4] = 5; int sum = 0; for(int i=0;i<nums.length;i++){ sum = sum + nums[i]; } System.out.println("总和为:"+sum); } } 运行结果为:总和为:15
1.数组int的默认初始值为0,string类型的默认初始值为null。就是当你没有赋值给他,然后要去输出它的时候,输出的结果为默认初始值。而当你的数组范围小于你要输出的值时,就会显示数组下标越界结果。即:Exception in thread "main"ArrayIndexOutOfBoundsException
2.堆和栈的区别,当你定义一个整型,而还没有new时,栈里面已经有数据了,当堆里面没有,只有当你new一个对象的时候,堆里面才开始有创建数据。
3.静态初始化: int[ ] a = {1,2,3}; Man[ ] mans = {new Man(1,1),new Man(2,2)};
动态初始化:int [ ] a = new int [ 2 ]; a[0]=1; a[1]=2;
package com.kuangsheng.Array; public class ArrayDemo02 { public static void main(String[] args) { int[] arrays = {1,2,3,4,5}; for (int i = 0;i<arrays.length;i++){ System.out.println(arrays[i]); } System.out.println("=============="); int sum = 0; for (int i = 0; i <arrays.length; i++) { sum = sum + arrays[i]; } System.out.println("总和为:" + sum); System.out.println("========="); int max = arrays[0]; for (int i = 1; i <arrays.length; i++) { if(arrays[i]>max){ max = arrays[i]; } } System.out.println(max); } } 运行结果: 1 2 3 4 5 ============== 总和为:15 ========= 5
package com.kuangsheng.Array; public class ArrayDemo03 { public static void main(String[] args) { int[] arrays = {1, 2, 3, 4, 5}; for (int array : (arrays)) { System.out.println(array); } printArray(arrays); } //打印数组元素 public static void printArray(int [] arrays) { for (int i = 0; i < arrays.length; i++) { System.out.print(arrays[i]+" "); } } } 运行结果: 1 2 3 4 5 1 2 3 4 5
package com.kuangsheng.Array; public class ArrayDemo04 { public static void main(String[] args) { int[][] array = {{1, 2}, {2, 3}, {3, 4}, {4, 5}}; printArray(array[0]); System.out.println(array[0][1]); } public static void printArray(int[] arrays) { for (int i = 0; i < arrays.length; i++) { System.out.print(arrays[i] + " "); } } } 运行结果: 1 2 2
package com.kuangsheng.Array; public class ArrayDemo05 { public static void main(String[] args) { int[][] array = {{1, 2}, {2, 3}, {3, 4}, {4, 5}}; // System.out.println(array.length);//4 // System.out.println(array[2].length);//2 for (int i = 0; i <array.length ; i++) { for (int j = 0; j<array[i].length;j++){ System.out.println(array[i][j]); } } } } 运行结果 1 2 2 3 3 4 4 5