An array in Java is a data structure that stores multiple values of the same type in a single variable. It is a fixed-size, ordered collection where each element is accessible using an index.
- Fixed Size: Once declared, the size of an array cannot be changed.
- Indexed Access: Elements are accessed using zero-based indexing (
array[0]
is the first element). - Same Data Type: All elements must be of the same type (e.g.,
int
,double
,String
, etc.). - Stored in Memory Contiguously: Arrays provide fast access to elements using indices.
Syntax
1 |
dataType[] arrayName = new dataType[size]; |
dataType
→ The type of values the array will store (e.g.,int
,double
,String
).arrayName
→ The name of the array.size
→ The number of elements the array can hold.
Declaring and Initializing an Array
1 2 3 4 5 6 7 8 9 10 11 12 |
// Declaration int[] numbers; // Allocation numbers = new int[5]; // Creates an array of size 5 // Initialization numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; |
Or, you can declare and initialize in a single step:
1 |
int[] numbers = {10, 20, 30, 40, 50}; |
Store Values in an Array
Once an array is created, we store values using indexing.
- Indexes start from 0, meaning the first element is at index
0
, the second at1
, and so on.
1 2 3 4 5 6 7 8 |
int[] numbers = new int[3]; // Array with 3 elements // Storing values numbers[0] = 10; // First element numbers[1] = 20; // Second element numbers[2] = 30; // Third element System.out.println("Stored values: " + numbers[0] + ", " + numbers[1] + ", " + numbers[2]); |
Output
1 |
Stored values: 10, 20, 30 |
Access and Change Values in an Array
We access and modify array elements using their index positions.
1 2 3 4 5 6 7 8 9 |
int[] numbers = {5, 15, 25, 35, 45}; // Accessing values System.out.println("First element: " + numbers[0]); // Output: 5 System.out.println("Third element: " + numbers[2]); // Output: 25 // Changing values numbers[1] = 100; // Changing the second element from 15 to 100 System.out.println("Updated second element: " + numbers[1]); // Output: 100 |