Arrays in Java
1. Definition
An array in Java is a data structure that stores multiple values of the same type in a single
variable. Each element in the array is identified by an index, starting from 0.
2. Rules for Using Arrays
- All elements must be of the same data type (e.g., int, float, String).
- The size of the array is fixed and defined at the time of creation.
- Array indices start from 0 and go up to array.length - 1.
- Accessing an index outside the array bounds throws ArrayIndexOutOfBoundsException.
- Arrays can be single-dimensional or multi-dimensional.
3. Syntax
Declaration Syntax:
dataType[] arrayName; // preferred
OR
dataType arrayName[]; // valid but less preferred
4. Declaration and Initialization
1. Declare and then Initialize:
int[] numbers; // declaration
numbers = new int[5]; // initialization (creates space for 5 integers)
2. Declare and Initialize in One Line:
int[] numbers = new int[5]; // all values default to 0
3. Declare with Values (Static Initialization):
int[] numbers = {1, 2, 3, 4, 5};