Computer >> Máy Tính >  >> Lập trình >> Java

Giá trị mảng mặc định trong Java


Java cung cấp cấu trúc dữ liệu, mảng, lưu trữ một tập hợp tuần tự có kích thước cố định của các phần tử cùng kiểu. Mảng được sử dụng để lưu trữ một tập hợp dữ liệu, nhưng thường hữu ích hơn nếu coi một mảng là một tập hợp các biến cùng kiểu. Khi một mảng được tạo mà không gán cho nó bất kỳ phần tử nào, trình biên dịch sẽ gán cho chúng giá trị mặc định. Sau đây là các ví dụ:

  • Boolean - false
  • int - 0
  • gấp đôi - 0,0
  • Đối tượng - 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 + " ");
      }
   }
}

Đầu ra

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