Introduction
In previous article, we learned control flow statements: if-else, switch, and loops.
Now, in this article, we’ll focus on storing and managing multiple pieces of data using:
Arrays – for collections of similar items
Strings – for text manipulation
StringBuilder & StringBuffer – for efficient string operations
By the end of this article, you’ll be able to store, access, and modify data effectively in Java programs.
1️⃣ Arrays in Java
An array is a container that stores multiple values of the same type in a single variable.
Syntax
dataType[] arrayName = new dataType[size];
Example:
int[] numbers = new int[5]; // array of 5 integers
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println(numbers[2]); // prints 30
Declare and Initialize in One Line
int[] numbers = {10, 20, 30, 40, 50};
String[] fruits = {"Apple", "Banana", "Orange"};
Access Array Elements
Use index (starts at 0)
System.out.println(fruits[0]); // Apple
System.out.println(fruits[2]); // Orange
Modify Array Elements
numbers[1] = 25;
System.out.println(numbers[1]); // 25
Array Length
System.out.println(numbers.length); // 5
Loop Through an Array
for(int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Or use enhanced for-loop:
for(int num : numbers) {
System.out.println(num);
}
2️⃣ Multi-Dimensional Arrays
Used to store tables or matrices.
Syntax
dataType[][] arrayName = new dataType[rows][columns];
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[1][2]); // 6
