Java cung cấp cấu trúc dữ liệu mảng (array), lưu trữ tập hợp tuần tự kích thước cố định các phần tử cùng kiểu. Mảng dùng lưu tập hợp dữ liệu, nhưng thường hữu ích hơn khi coi mảng là tập hợp biến cùng kiểu. Khi mảng được tạo mà không gán phần tử, compiler gán giá trị mặc định. Ví dụ:
- Boolean -
false - int -
0 - double -
0.0 - Object -
null
Ví dụ
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 + " ");
}
}
}
Kết quả
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