Array Introduction-tutorial
In Java, an array is an object that stores a fixed-size sequence of elements of the same data type. Arrays are used when you want to store multiple values of the same type in a single variable.
How to Declare and Initialize Arrays in Java
1. Declaration Only
Both declarations are valid and widely used in Java.
2. Initialization After Declaration
3. Declaration + Initialization
Example: Java Array Declaration and Initialization
Output:
Key Features of Arrays in Java
- Arrays hold similar types of data (e.g., only integers or only strings).
- The array has a fixed size (cannot grow/shrink once declared).
- Array elements are stored in contiguous memory.
- Arrays are zero-indexed (i.e., the first element is at index 0).
- You can access any element randomly using its index.
- Java arrays are objects; they inherit from the Object class and implement Serializable and Cloneable.
How to Declare and Initialize Arrays in Java
1. Declaration Only
// Method 1int integerArray[ ];
// Method 2int[ ] integerArray;
Both declarations are valid and widely used in Java.
2. Initialization After Declaration
integerArray = new int[10]; // Array of size 10 (all values default to 0)
3. Declaration + Initialization
int[ ] integerArray = new int[10]; // Array with default values
int[ ] numbers = {1, 4, 6, 8, 10}; // Array initialized with specific values
Example: Java Array Declaration and Initialization
public class ArrayExample { public static void main(String[ ] args) { int[ ] numbers = {1, 4, 6, 8, 10}; // Declaration + initialization
// Accessing elements System.out.println("First Element: " + numbers[0]); System.out.println("Third Element: " + numbers[2]);
// Looping through the array for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); } }}
Output:
First Element: 1 Third Element: 6 Element at index 0: 1 Element at index 1: 4 Element at index 2: 6 Element at index 3: 8 Element at index 4: 10