1. ホーム
  2. Java

ジャバアレイ

2022-02-10 12:41:54

java配列の静的・動的初期化、フォーマットと留意点

/**
 * java arrays are static and must be initialized before they can be used, and once the initialization specifies the length of the array, that length is immutable.
 * 
 * 
 * 
 * A: Format for static initialization of arrays.
 * Format: datatype[] array name = new datatype[]{element1,element2,...};
 * Initialization display specifies the initial value of each array element, and the system determines the length of the array
 * Simplified format.
 * datatype[] array name = {element1,element2,...};
 * 
 * B:Dynamic initialization of java arrays
 * Dynamic initialization: that is, as opposed to static initialization.
 * Actually dynamic initialization is specifying the length of the array at the time of initialization (when memory is already allocated)
 *  
 *  
 * Note: All local variables are stored in stack memory.
 * whether they are actually variables of basic type or reference type, they are stored in the respective method stack area.
 * However, objects referenced by reference type variables (including data, ordinary java objects) are always stored in heap memory.
 *  
 * Arrays in Java are reference variables (similar to pointer variables in C), and after we initialize the operation
 * is pointing its reference to a contiguous memory space of the specified length opened up in heap memory.
 * So what we're really doing is initializing the array variable on the stack to point to valid memory.
 *  
 *  
 * Two exceptions related to arrays
 * a:ArrayIndexOutOfBoundsException: array index out of bounds exception
 * Cause: You accessed an index that does not exist.
 * b:NullPointerException:Null pointer exception
 * Cause: The array is no longer pointing to heap memory. And you still use the array name to access the elements.
 * int[] arr = {1,2,3};
 * arr = null;
 * System.out.println(arr[0]);
 */
public class f {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// datatype[] array name = new datatype[]{element1,element2,...};
		int[] arr = new int[]{11,22,33,44,55};
		//int[] arr = new int[5]{11,22,33,44,55}; //Cannot define dimension expression
		//Cannot define dimension expressions when an array initializer is provided
		int[] arr2 = {11,22,33,44,55}; //Short form of static initialization

		int[] arr3; //declare an array reference
		arr = new int[]{11,22,33,44,55};

		int[] arr4;
		//arr2 = {11,22,33,44,55}; //short form declaration and assignment should be on the same line
		//Array constants can only be used in initializers
		System.out.println(arr2);
		System.out.println(arr2[4]);
	}
}