Arrays help you store many values in one place. This makes it easy to keep and use groups of data together.
Array declaration and initialization in Java
public class ArrayExample { public static void main(String[] args) { // Declare an array of integers int[] numbers; // Initialize the array with size 5 numbers = new int[5]; // Or declare and initialize at the same time int[] scores = new int[3]; // Declare and initialize with values String[] names = {"Alice", "Bob", "Charlie"}; } }
You declare an array by specifying the type followed by square brackets [].
You initialize an array by creating it with a size or by giving values directly.
int[] emptyArray = new int[0];
int[] singleElementArray = new int[1]; singleElementArray[0] = 10;
String[] fruits = {"Apple", "Banana", "Cherry"};
double[] prices = new double[]{2.5, 3.0, 4.75};
This program shows how to declare arrays, print their default values, assign new values, and print them again. It also shows how to declare and initialize a String array with values directly.
public class ArrayDeclarationInitialization { public static void main(String[] args) { // Declare and initialize an integer array with size 4 int[] ages = new int[4]; // Print default values System.out.println("Ages before assignment:"); for (int index = 0; index < ages.length; index++) { System.out.println("ages[" + index + "] = " + ages[index]); } // Assign values to the array ages[0] = 21; ages[1] = 25; ages[2] = 30; ages[3] = 28; // Print values after assignment System.out.println("\nAges after assignment:"); for (int index = 0; index < ages.length; index++) { System.out.println("ages[" + index + "] = " + ages[index]); } // Declare and initialize a String array with values String[] cities = {"New York", "London", "Tokyo"}; System.out.println("\nCities array:"); for (int index = 0; index < cities.length; index++) { System.out.println("cities[" + index + "] = " + cities[index]); } } }
Arrays have a fixed size once created. You cannot change their length later.
Default values for int arrays are 0, for objects like String they are null.
Accessing an index outside the array size causes an error (ArrayIndexOutOfBoundsException).
Arrays store multiple values of the same type in one variable.
Declare arrays with type[] and initialize with size or values.
Use loops to access or change array elements by their index.
