Java提供了一个数据结构,即数组,该数组存储一个固定大小的相同类型元素的顺序集合。数组用于存储数据的集合,但是将数组视为相同类型的变量的集合通常会更有用。在创建数组而未为其分配任何元素的情况下,编译器会为其分配默认值。以下是示例:
Boolean - false
int - 0
double - 0.0
Object - null
public class Tester { public static void main(String[] args) { System.out.print("Default values (String array):"); String strings[] = new String[5]; for (String s : strings) { System.out.print(s + " "); } System.out.println(); System.out.print("Default values (int array):"); int numbers[] = new int[5]; for (int val : numbers) { System.out.print(val + " "); } System.out.println(); System.out.print("Default values (double array):"); double doubles[] = new double[5]; for (double val : doubles) { System.out.print(val + " "); } System.out.println(); System.out.print("Default values (boolean array):"); boolean booleans[] = new boolean[5]; for (boolean val : booleans) { System.out.print(val + " "); } System.out.println(); System.out.print("Default values (Object array):"); Tester testers[] = new Tester[5]; for (Tester val : testers) { System.out.print(val + " "); } } }
输出结果
Default values (String array):null null null null null Default values (int array):0 0 0 0 0 Default values (double array):0.0 0.0 0.0 0.0 0.0 Default values (boolean array):false false false false false Default values (Object array):null null null null null